I can add an overlay, but I cannot remove it (jQuery)
This function adds an overlay with the following properties to the entire browser screen,
$('a.cell').click(function() {
$('<div id = "overlay" />').appendTo('body').fadeIn("slow");
});
#overlay
{
background-color: black;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
display: none;
z-index: 100;
opacity: 0.5;
}
And this function should remove it.
$('#overlay').click(function() {
$(this).fadeOut("slow").remove();
});
But it doesn't do anything and now my page is stuck over black over it. What happened to the deletion?
source to share
The problem is click
there is no overlap when adding a handler , so you add the handler to an empty stencil.
To fix this, use the live method to bind your handler to all elements that match #overlay
when they are created.
Also, fadeOut
it is not a blocking call, so it returns before the element finishes fading. Therefore, you call remove
right after the element starts to fade away.
To fix this, use the fadeOut
callback parameter to be called remove
after the animation has finished.
For example:
$('#overlay').live(function() {
$(this).fadeOut("slow", function() { $(this).remove(); });
});
source to share
My recommendation is to use the jquery.tools overlay plugin . Your overlay will have a trigger (usually a button or link), but you can load or clear it with a javascript command like:
JS:
var config = { closeOnClick:true, mask:{opacity:0.7, color:'#333', loadSpeed:1} }
$("#myTrigger").overlay(config); // add overlay functionality
$("#myTrigger").data("overlay").load(); // make overlay appear
$("#myTrigger").data("overlay").close(); // make overlay disappear
HTML:
<div id="myOverlay" style="display:none;">Be sure to set width and height css.</div>
<button id="myTrigger" rel="#myOverlay">show overlay</button>
source to share