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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

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