Wednesday, January 13, 2010

Disabling The Background Behind Popup Layers

An application that I am building is using a lot of popup layers to manage content for ease of use and navigation. I had the urge to not only pop up a layer with a content administration form in it, but also disable the background behind that popup to prevent any interaction with links and buttons behind that layer.

I have never had to do that manually before, as I have used JavaScript libraries, such as the Yahoo YUI or the like, that had that feature as part of the package and it was done automatically. I was pleasantly surprised to find out it wasn't nearly as complex as I thought it'd be.

For starters, you need to add an empty div with the id of "backgroundFilter".

With that, add the style for it into your style sheet:
#backgroundFilter
{
position: absolute;
top: 0;
left: 0;
overflow: hidden;
padding: 0;
margin: 0;
background-color: #333333;
filter: alpha(opacity=50);
opacity: 0.5;
display: none;
z-index: 1;
width: 100%;
height: 100%;
}
In addition, whatever styles are assigned to your popup windows, they need to have a higher z-index than this div. So anything higher than z-index:1 will work.

A final step is adding the JavaScript to handle it. Put this in any available JavaScript:
function backgroundFilter()
{
var div;
if(document.getElementById)
div = document.getElementById('backgroundFilter');
else if(document.all)
div = document.all['backgroundFilter'];
if(div.style.display==''&&div.offsetWidth!=undefined&&div.offsetHeight!=undefined)
div.style.display = (div.offsetWidth!=0&&div.offsetHeight!=0)?'block':'none';
div.style.display = (div.style.display==''||div.style.display=='block')?'none':'block';
}
Then, wherever you have your JavaScript functions to show and hide layers, put a call to this function at the end of it so it gets called after any div is popped up or taken down, the function will see it, and act accordingly to disable or enable the main screen.

It's as easy as that!

0 comments: