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?

+2


source to share


5 answers


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(); });
});

      

+9


source


Here you go. This should fix the problem and allow the overlay to fade out before removing.



$('#overlay').live("click", function()  {
        $(this).fadeOut("slow", function() { $(this).remove() });
});

      

+3


source


Delete should be in the fade out callback, for example:

$('#overlay').live('click', function()  {
    $(this).fadeOut("slow", function() {
       $(this).remove();
    });
});

      

+2


source


Try:

$('#overlay').live('click', function()  {
        $(this).fadeOut("slow").remove();
});

      

+1


source


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>

      

0


source







All Articles