Search code examples
jqueryslideupjquery-callback

Jquery slideUp callback function when initial selector includes child


How can I add a callback function to the slideUp() function if the initial selector I am using includes children()?

$('.homebuttonbutton').hover(function() {
        $(this).stop().children('.homebuttonaction').slideDown();
        $(this).children('.homebuttonlabel').addClass('whitebutton');
    }, function() {
        $(this).stop().children('.homebuttonaction').slideUp(300, function() {
             $(this).children('.homebuttonlabel').removeClass('whitebutton');
        });
        //$(this).children('.homebuttonlabel').removeClass('whitebutton');
    });

So ideally, when hovered, the child .homebuttonaction slides down and has the .whitebutton class added, and then when un-hovered, the .homebuttonaction slides up and the .whitebutton class is removed.

I'm hoping to have the class removed AFTER the slideUp animation is finished, but I'm not sure how to 'select' it, as the initial selector is using children for the callback function.

There are going to be multiple .homebuttonaction classes, so I can't just use

$('.homebuttonaction').removeClass('.whitebutton');

because then it would apply to every one, right? Does the callback function treat $(this) as the item being selected in the first place, or as the current selected item that was found through children()?

Thanks for the help, SO.

EDIT Here is my fiddle - http://jsfiddle.net/kcxWc/ - as you can see, the class is not removed as it should be AFTER the slideUp effect is over. I believe it is a selector issue...


Solution

  • this will refer to a .homebuttonbutton object in the mouseenter / mouseleave calbacks, and to a .homebuttonlabel object in the slideUp callback.

    To refer the .homebuttonbutton inside the callback, you can seach the dom tree, or capture a reference to it in a closure.

    Traversing the dom tree:

    $(this).stop().children('.homebuttonaction').slideUp(300, function() {
        $(this).closest('.homebuttonbutton').children('.homebuttonlabel').removeClass('whitebutton');
    });
    

    Capturing in a closure:

    var homeButton = $(this);
    $(this).stop().children('.homebuttonaction').slideUp(300, function() {
        homeButton.children('.homebuttonlabel').removeClass('whitebutton');
    });