How to make an invisible overlay layer work on IE

Making an invisible overlay layer work on IE

It’s becoming more and more common on the web to create pages that, on some situations, display some object over the page content. This could be a photo (using LightBox), a movie (like Apple does on their trailers site for non-HD trailers), a dialog, a color-picker, etc. In that situation, you often want to make the object go away when the user clicks anywhere on the page but the object.

One technique I use often is to create a DIV with no content or background that covers the entire page, place it on the page with z-index above the page content and below the displayed object, and bind it’s onClick event handler to a method that hides the object and the DIV itself. Something like this:

overlay work on ie

As you can see, the transparent layer (represented here in blue) gets between the object to float above the page content (here, in red) and the page itself.

So, how hard can it be, right? Just do some quick Javascript code or use CSS to set the DIV properly, handle onClick, and you are done… or not. Yes, IE. IE will screw this all up.

When I implemented this recently, I noticed that, on IE, the mouse click would go through the overlay to the page itself, clicking on links or buttons, or simply not hiding the floating object because the layer onClick was never triggered. Even weird, on some areas of the page it worked, and on other areas it didn’t. It depended on what was below it.

After gooling and trial-and-error for a while, I found the solution. The problem is that IE doesn’t like handling clicks on transparent objects, like DIVs with no content or background. So, the solution is… add a background. But wait, if you add a background, it won’t be transparent any more, right? Wrong. There’s a neat trick you can use: create a transparent GIF file with about 200*200 and use it as the background of the DIV (the size is irrelevant for this, but if it’s too small, it will make browsers on old computers slow when reproducing it to fill all the background). IE will work, because from it’s point of view, there is SOMETHING there belonging to the DIV (even if it’s a transparent GIF) and the onClick will be triggered as expected.