March 17, 2012

jQuery animate() callback not working right with removeClass()

Question by Antonio Vitor

Hey guys I’m working on a jQuery code snippet that’s suppose to remove a class from an object after the animation has been completed. This is what I have so far:

$('.box').hover(function() {
        $(this).stop().addClass('active').animate({ 'margin-top': '-49px' }, 500);
    }, function() {
        $element = $(this);
        $(this).stop().animate({ 'margin-top': '0' }, 500, function() {
            $element.removeClass('active');
        });
    });

The problem is that sometimes when the animation completes the class is not removed. This happens when I move too fast between divs.

You can view an example here in the slider section there are three boxes inside the slider that says ‘City’, ‘House’, and ‘Business’.

Any help is appreciated.

PS the same thing happens on the main navigation, sometimes the sub-nav just hangs there. Here is the code for the navigation:

$('#navigation ul li').hover(function(){
        $("a:eq(0)", this).addClass("hover");
        $(this).find('ul:eq(0)').stop(true, true).slideToggle();
        }, function(){
            $("a:eq(0)", this).removeClass("hover");
            $(this).find('ul:eq(0)').stop(true, true).slideToggle();
        }
    );

Answer by Starx

Change your $element declaration to this

var $element = $(this);
...

Please fill the form - I will response as fast as I can!