Create a Modal Dialog Using CSS and Javascript

Written by and published



Back in my early programming days, before I switched over to web development, I spent most of my time writing software for Windows. I look back on that time with fond memories. 8-bit icons, OLE2, and no silly Start menus.

With the recent Web 2.0 boom, many web developers have returned to their roots and begun building sites that resemble desktop applications. AJAX (the second coming of javascript) lets designers borrow elements from the desktop paradigm and use them on their websites.

One element that I find myself using quite a bit are modal dialogs. In a desktop application, a modal dialog is a box or message that forces you to dismiss it before you can use any other part of the program. When used sparingly, it can be a great way to direct the user’s attention to a specific element and force them to make a decision. With a little CSS and Javascript we can accomplish this same effect on the web.

Measure the impact of your design changes on your site’s performance with Raven’s Site Auditor, rank tracking and Google Analytics integration. Sign up for a free 14 day trial of Raven Tools and get started in minutes.

The code behind this effect is surprisingly simple. There are three pieces involved:

  • A <div> containing the content you want to appear when the modal area is activated.
  • Two CSS rules which keep the layer hidden until needed and then “fullscreen” when activated.
  • Javascript which hides and shows the <div>.

The overlay <div>

At the bottom of your HTML, create a <div> with id = “overlay”. Any content placed inside this area will initially be hidden by the browser and then shown modally when activated. Any content beneath it will be “unclickable” by the user, which forces them to interact with whatever message you give them.

Inside #overlay I usually place another <div> which I center horizontally and apply a few styles to create a dialog box appearance. It’s this second <div> that actually contains the content I’m showing the user.

<div id="overlay">
     <div>
          <p>Content you want the user to see goes here.</p>
     </div>
</div>

The CSS

There’s only one CSS rule to take care of the fullscreen/hiding for #overlay.

#overlay {
     visibility: hidden;
     position: absolute;
     left: 0px;
     top: 0px;
     width:100%;
     height:100%;
     text-align:center;
     z-index: 1000;
}

You can style the inner <div> however you like. As I said above, I usually center it horizontally to give it more of a dialog box look and feel.

#overlay div {
     width:300px;
     margin: 100px auto;
     background-color: #fff;
     border:1px solid #000;
     padding:15px;
     text-align:center;
}

The Javascript

The javascript that controls everything is insanely simple. Just add the following function to wherever you’re storing your javascript. (That could be in the <head> of your document or in an external .js file.)

function overlay() {
	el = document.getElementById("overlay");
	el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}

The javascript grabs our overlay element and then toggles its visibility property. If it’s hidden, it makes it visible and vice versa. You could create a function to explicitly show or hide the layer, but I prefer this automatic toggle method since it requires less code.

With the function in place, we then call it whenever we want to show the overlay and then again to hide it. So, somewhere on our page we could add

<a href='#' onclick='overlay()'>Click here to show the overlay</a>

When the user clicks on the link our javascript will show the overlay.

Within the overlay’s HTML, we need to add a link to hide it. The code is exactly the same:

Click here to [<a href='#' onclick='overlay()'>close</a>]

Finishing Touches

When the user clicks the link to show the overlay, they may become confused since it looks like they can still click on any element in the page. To help them understand what’s going on, we can apply a background image to the overlay <div>. In Photoshop I create a simple checkerboard pattern .png with transparency. This creates a shaded effect so the user can still see the underlying web page but know not to click on it. To add the background to the layer, add the following to our CSS.

#overlay {
     visibility: hidden;
     position: absolute;
     left: 0px;
     top: 0px;
     width:100%;
     height:100%;
     text-align:center;
     z-index: 1000;
     background-image:url(background-trans.png);
}

And finally, (as always) we need to add a small tweak so that this works in Internet Explorer. Fortunately, it’s quick fix. Add this to your CSS.

body {
     height:100%;
     margin:0;
     padding:0;
}

In order for an element to have a percentage height applied to it (which #overlay does), IE requires the parent element to have a height. So, just set body’s height to 100% and zero the margins and we’re all set!

Update:

Reader Henrik Binggl commented that this technique doesn’t work on form elements in IE6. I did some digging and found an article on MSDN that explains the problem, which, as it turns out, only applies to <select> elements — not all form elements. In short, they are rendered as a seperate window by IE which floats above all other page content regardless of their z-index. There is a workaround, but it’s complicated and messy. The Microsoft page recommends waiting as the problem has been fixed in IE7.

70 Responses to “Create a Modal Dialog Using CSS and Javascript”

  1. Henrik Binggl

    perfect … but:
    just perfect look in firefox. but a problem with ie6. i have a number of select fields. they are somewhere above the overlay (z-index)?
    any solution?

  2. You’re right about being able to navigate to the other links via the keyboard, but I don’t know of any easy way around this. Off the top of my head, the only solution I can think of would be some javascript that attaches an onfocus event to all links not contained inside the modal div layer. When onfocus is fired, if the div layer is visible, restore focus to the modal area.

    Anyone want to write this? 🙂

  3. Very nice, although I have a strange problem in FF1.5. If I put a form inside the modal div, I can’t see the blinking cursor when I click an input control or a textarea. Have any idea why this happens?

  4. a workaround to disable the under-layer stuff (buttons, links, etc): put the background layer and the popup layer in two separate divs and finally include them in a third. add a background color to the background layer with opacity filter (this disables all the stuff under), add a background color to the popup (this way it will be able to be 100% opaque, since it is not nested in the background and thus will not be transparent also). finally the toggle needs to be triggered on both layers at the same time, that is why you need to put both in a third container.

    and here it goes in code (i use a different positioning method, so do not be fooled by that. i use this one coz it positions to the center vertically too):

    CSS –>
    .poptogg {
    visibility:hidden;
    }
    .popback {
    position:absolute;
    left:0px;
    top:0px;
    width:100%;
    height:100%;
    background:#000000;
    filter:alpha(opacity=60);
    opacity:.60;
    }
    .popstyle {
    position:absolute;
    left:50%;
    top:50%;
    margin-top:-100px;
    margin-left:-100px;
    width:200px;
    height:200px;
    background:#000000;
    }

    HTML –>

     

    Wahtever text.
    close window

    JAVASCRIPT –> the same as above

  5. Okay, I know this is far fetched, but I came upon the following problem in firefox 1.5:

    I implemented the modal dialog described above and i had it defined over a div with overflow:auto. When the dialog is not being shown, the rendering of the div below gets funked up. Each time, parts of the div are being shifted either vertically or horizontally.

    If you come up against this problem, a solution for this is to change the property hiding the dialog to display:none instead of visibility:hidden.

    Also in the function change to:

    el.style.display= (el.style.display == “block”) ? “none” : “block”;

    • Saeed Sobhani

      Your problem would be solved with this code:
      function overlay() {
      var el = document.getElementById(“overlay”);
      el.style.visibility = (el.style.visibility == “visible”) ? “hidden” : “visible”;
      $(‘#overlay’).css(‘position’, ‘fixed’);
      }

  6. Couple Newbie questions…

    I put the #overlay{} and #overlay div {} in between style tags and this works. If I put this in a StyleSheet.css (using Visual Studio 2005) it doesn’t.

    Also, I have not been successful getting the background-image:url(overlay.gif) to work. I have created one and put it into a project folder called Images.

    TIA.

  7. Nice article. This works fine but I have some additional features to be added to this. I need a movable dialog. Can anyone suggest me how to make this modal dialog movable?

  8. @Pavel: Indeed there is a problem with scrolling, however, I fixed it by creating a div for the lower layer inside the body of the html (not containing the overlay div).

    #the-body {
    height: 100%;
    width: 100%;
    overflow:auto;
    margin:0;
    padding:0;
    }

    In this div you put your actual body, and leave the overlay stuff outside.

  9. Rizwan Liaquat

    This is simply not the way to create modal dialog boxes. This code as lots of problems in scrolling & in disabling the background content

  10. Vandana

    Can someone help me.. why blinking cursor is not visible on text field over a frame. This Problem is coming in firefox.. Plzzzzz suggest what to do..??

  11. FYI, for those of you have problems with your dropdown boxes showing through; put a div around all of your controls(say we call it “mainDiv”. Then, in the javascript where you show the modal(“overlay”) div, you can use the CSS display option to hide all of those controls, including the dropdowns.

    ie:

    document.getElementByID(“overlay”).style.visibility = “visible”;
    document.getElementById(“mainDiv”).style.display = “none”;

    This works in IE6 to hide all of your controls, which makes the dialog less confusing.

  12. I have written something very similar to this, and I came across this looking for a fix to this bug I have and it seems you have the same issue as me. If you resize the browser window up far enough to where a scroll bar pops and you scroll down, the transparency div cuts off. It isn’t too big of a deal.. Just annoying. Please let me know if you find a fix for this.

  13. I don’t know why my post got deleted but I have discovered a workaround to a bug you are having when resizing the page small enough to where a scroll bar shows, and you scroll down, the transparency is cut off. For IE dynamically change the body overflow to hidden and then back to auto when closing the overlay. Works the same in FF except the scrollbar disappear, the overlay just sits over it. To fix that, make a div around the contents of the body with width and height 100% and change that overflow dynamically as well.

  14. Another weird problem. My modal dialog box appears, but only for a split second, then its goes away. Can’t figure out why it just flashes up there for only a second. Any ideas? Thx

  15. #27: I was messing around with the code and did something that caused the dialog box/modal window to flash by real quick. Sorry, don’t recall what it was I had done to cause that!

    #26: I solved this transparency problem by setting #overlay’s height to 500% (you can use whatever arbitrary value to cover the length of your page).

    #5: The subModal code is wonderful (and thank you for your contribution to it) but it’s really complicated and I can’t figure it out; nothing a relative n00b can hack, unlike this code. Moreover, subModal causes horizontal scrollbars to appear in Firefox 2! There’s a solution that’s been very (very) briefly mentioned in the subModal newsgroup of Google Groups but, like I said, the subModal code is way too complicated for n00b hacks like me to figure out how to customize, much less fix! =(

    Everybody: Do you have problems with this present sitening.com modal window code in MSIE 7, where loading time is concerned?? For some reason, IE7 takes 100% CPU capacity to load the background .png!! Resizing the browser window also takes almost half a second to render!!!

  16. Correction to #29 above:

    Resizing browser window can take almost half a *minute* in MSIE7, though I have 1GB of system RAM (and 128MB of dedicated video RAM) running only WinXP SP2 with a P1.6GHz Pentium Mobile. For some reason, loading the .png in MSIE7 is not instantaneous.

    Also, as for the suggestion to the transparency/opacity “cut-off” problem, setting #overlay’s height to a higher value, it will create “dead space” to the end of the webpage…the transparency .png will be stretched, but along with it your webpage, creating unnecessary space — unless you calculate the exact percentage needed to cover the particular webpage but not go over it (and thus creating that dead empty space)….

  17. ajclifford

    This worked great for me. I hadn’t played with overlay’s before now and this was a great introduction. Thanks very much for your nice easy code to follow.

  18. ajclifford

    Hmm, like PaW, I too am having IE7 completely lock up with 50%+ CPU usage, if you wait it will eventually load, until you click something again of course. Any ideas?

  19. ajclifford

    It turned out that it was the very small background image causing the problem as it was being redrawn on the x and y axis. If you replace this tiny image with a bigger one, say 100×100 in size this remove the performance hitch in IE7. Hope this helps others, thanks.

  20. Airmax

    First of all, thank you very much for this code is very usefull.

    And I would like to add something… I would like to disable scrollbars when the “modal” div is actived, adding four lines at the end of the overlay function:

    Is the same as says wishcow, but is not necessary to add “the-body” layer.

    function overlay() {
    el = document.getElementById(“overlay”);
    el.style.visibility = (el.style.visibility == “visible”) ? “hidden” : “visible”;

    if (el.style.visibility == “visible”)
    document.body.style.overflow = “hidden”;
    else
    document.body.style.overflow = “auto”;
    }

    Regards and Thanks

  21. Priyanka

    Hi!

    I have implemented something similar to your modal dialog. The problem I am facing is that when I click on one of the buttons another modal dialog is displayed. The buttons on the first dialog can still be accessed. I was wondering if there was a way to disable (make it look like its a part of the background) the first dialog when the second one comes up?

  22. Gopinath

    Hi ..

    I have tried this and it works fine for me.Its a simple overlay function just to display its functionality how it works rather than other cons and people should notice this.

    Thanks a lot.

  23. I have been tweaking the overlay and now I’m trying to make it fade in and out. Has anyone done this or is willing to share how to approach this?

    Its very clean and simple but I do really miss a transition fade 🙂

  24. I know it’s years after the fact, but in your overlay function, you need to declare the variable like this:
    var el = document.getElementById(“overlay”);
    instead of just:
    el = document.getElementById(“overlay”);

    I was copying your code to do a quick overlay, and it didn’t work in IE8 until I fixed that line. Thanks for saving me a lot of effort though!

  25. Hi,

    this is quite an old post, but I found a solution to control the tab behaviour of the links. I tried this in IE6 and 8 and Firefox, but this requires, that you avoid using the attribute “tabindex” at your page.

    First, you need to set the attribute tabindex to all links inside the dialog. You can use numbers twice. The following JavaScript will disable focussing all links without a tab index and sets the focus to the lowest element.

    var l = document.links.length;
    var f = window.undefined;
    for(var i=0; i<l; i++) {
    e = document.links[i];
    if (e.tabIndex == 0) {
    e.onfocus = function() {
    document.links[f].focus();
    }
    } else if (!f && e.tabIndex == 1) {
    f = i;
    }
    }
    if (f == window.undefined) {
    f = 0;
    }

    Please note, this is quite simple. I hardcoded the "1" to avoid 2 loops over all links. You can also use a loop before my code to set "tabindex" via script to all links inside the dialog. For that, use

    document.getElementById("overlay").getElementsByTagName("a");

    Have fun! 🙂

  26. Hallion91

    E-X-C-E-L-E-N-T

    Very good job ! Thanks for the function-natured overlay, I had headaches trying to make my overlay work in nested calls and there I find this : a function !!

  27. Maximiliano

    Man,

    Usually, the most people use JQuery, me too, but, the page that I was working, it was very complicated, too bad code and bad css, so JQuery wasn’t functional properly, so, your tips help me a lot to to may own modal windowl!!!! Thanks!

  28. Ajay - TechSoul

    Sorry ! it was the setting problem in Chrome, if you also got like this Problem then goto Chrome Controls > Tools > Encoding > and select the Top “Unicode (UTF-8)”.

  29. Ajay - TechSoul

    Sorry ! it was the setting problem in Chrome, if you also got like this Problem then goto Chrome Controls > Tools > Encoding > and select the Top “Unicode (UTF-8)”.

  30. scientista

    my background is coming out transparent, even when I don’t use an image. Is there a way to fix this? I want the background to be transparent but the inner div to be solid. I’ve been scanning discussions, and it seems that this isn’t possible unless you use a separate div (couldn’t get that to work for some reason). I tried using a .png file with transparency for just the outer background, but for some reason the .png image transparancy is carrying on to the inner div. Help would be much appreciated!

  31. F Santoke

    This is great for alerts and images. Exactly what I was looking for.
    Is there any way to use this to display a child page (like email.htm). I can have it within div on the same page, but would prefer another page. Is it possible??

  32. F Santoke

    This is great for alerts and images. Exactly what I was looking for.
    Is there any way to use this to display a child page (like email.htm). I can have it within div on the same page, but would prefer another page. Is it possible??