RCNeil
RCNeil

Reputation: 8779

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...

Upvotes: 1

Views: 321

Answers (2)

Ortiga
Ortiga

Reputation: 8824

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

Upvotes: 0

Brad M
Brad M

Reputation: 7898

You don't always have to rely on the "this" keyword. Those functions are passed the event object, and you can find the "item selected" by the event.target property. For example.

$('.homebuttonbutton').hover(function(event) {
    var onlyTheButtonThatWasClicked = event.target;
});

Upvotes: 1

Related Questions