Matt Ryan Matt Ryan - 6 months ago 14
jQuery Question

Why is my jQuery animation not working?

I use jQuery animate all the time, but it is failing for some reason this time. It will work it I try to target '$(this).animate' after the closeBtn click, and it will work, kinda.

here is a portion of my html(the relivant parts, and yes I have called the jQuery library)

<div id='lightBox' style="opacity:0;">
<div id='closeBtn'>
</div>
<div id='lightBoxContent'>
</div><!--lightBoxContent-->
</div><!--lightBox-->


here is my jquery

$(document).ready(function()
{
$('#quoteBtn').click(function()
{
$('#lightBox').animate({
opacity:'1',
height:'560px'
}, 300, function() {
$('#lightBoxContent').html(output);
});


$('#closeBtn').click(function()
{
//alert('click');
$('#lightBox').animate({
opacity:'0'
}, 300, function() {
//alert('first animation complete');
$('#lightBox').animate({
height:'0px'
}, 300, function() {
//alert('second animation complete');
});
});
});
});
});


and my css(it is not really a requirement for this, but I included it for safe measure

#lightBox {
width:780px;
background-color:white;
position:fixed;
margin-left:-400px;
margin-top:-300px;
left:50%;
top:50%;
z-index:9999;
-webkit-box-shadow: 0px 0px 200px 50px ;
box-shadow: 0px 0px 200px 50px ;
padding:20px;
}

Answer

You want to move $('#closeBtn').click(function() outside of the click() function being called when #quoteBtn is click. Because it will never be called since you can't click inside of a click.

Here is what it should look like:

$(document).ready(function()
{ 
    $('#quoteBtn').click(function()
    {
        $('#lightBox').animate({
            opacity:'1',
            height:'560px'
        }, 300, function() {
            $('#lightBoxContent').html(output);
        });    
    });

    $('#closeBtn').click(function()
    {
        //alert('click');
        $('#lightBox').animate({
            opacity:'0'
        }, 300, function() {
            //alert('first animation complete');
            $('#lightBox').animate({
                height:'0px'
            }, 300, function() {
                //alert('second animation complete');
            });
        });
    });

});

Update: Ok... here is part 2.

You want to set $('#lightBox').animate({ to $('#lightBox').stop().animate({ which will then continue the "close" animation.