jQuery get source element in callback
Asked Answered
B

3

5
$('.myElem').live('click', function() {
    $(this).hide(500, function() {
        $(this).siblings('.myOtherElem').show();
    });
});

The above doesn't work because $(this) is no longer in correct scope in the callback. How do I pass my original source element into the callback?

Barry answered 7/7, 2010 at 13:29 Comment(0)
L
7

Actually your code should work.

To access this within an inner javascript method you might store the reference in the outer method scope:

$('.myElem').on('click', function() {

   var myElem = this;    
    $(this).hide(500, function() {
        $(myElem).siblings('.myOtherElem').show();
    });

});

However in most jQuery methods this is referring to the selector or element used:

$('.myElem').on('click', function() {
    // This refers to the clicked element
    $(this).hide(500, function() {
       // This refers to the clicked element as well 
       $(this).siblings('.myOtherElem').show();
    });    
});
Lipstick answered 7/7, 2010 at 13:33 Comment(0)
P
2
$('.myElem').live('click', function() { 
    var $this = $(this);
    $this.hide(500, function() { 
        $this.siblings('.myOtherElem').show(); 
    }); 
}); 
Peg answered 7/7, 2010 at 13:31 Comment(0)
T
0
$('.myElem').live('click', function() {
    $(this).hide(500);
    $(this).siblings('.myOtherElem').show();
});
Timely answered 7/7, 2010 at 13:35 Comment(2)
That won't accomplish the same thing. Putting the .show() call in the callback ensures that it won't happen until the .hide() animation is completed. The code in your answer will cause them to both happen nearly simultaneously.Ugrian
You could do it by using delay: .delay(500).show(1) However using the show callback is the better solution.Lipstick

© 2022 - 2024 — McMap. All rights reserved.