Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery nested this references [duplicate]

I have some JQuery Code as follows:

$("#sh-zone-button-cart-menu").live("click", function(event)
{
    event.preventDefault();
    $("#sh-zone-cart-menu").toggle(0, function(){
        if($(this).is(":visible")){
            $(this).siblings(".sh-zone-button-link-menu-content").hide();
            $("#sh-zone-button-cart-menu").parent().removeClass("current");
            //need to reference (this) for $("#sh-zone-button-cart-menu") here 
        }               
    });
    $("#sh-zone-button-cart-menu").parent().toggleClass("current"); 
});

I am trying to access the this reference for my initial click from within another sub-element i.e. I would like to get the this reference that would have been available just after the first curly brace of my live() method. However, I need access to it from within another sub-element i.e. inside my toggle() method.

How can I do this?

Thanks.

like image 265
ObiHill Avatar asked May 04 '11 20:05

ObiHill


3 Answers

Save this as a local variable:

$("#sh-zone-button-cart-menu").live("click", function(event) {
    // This line saves the current 'this' as a local variable 
    // that can be accessed by inner functions        
    var thisInClick = this;
    event.preventDefault();
    $("#sh-zone-cart-menu").toggle(0, function(){
        if($(this).is(":visible")){
            $(this).siblings(".sh-zone-button-link-menu-content").hide();
            $("#sh-zone-button-cart-menu").parent().removeClass("current");
            //need to reference (this) for $("#sh-zone-button-cart-menu") here 
            $(thisInClick).doSomething();
        }               
    });
    $("#sh-zone-button-cart-menu").parent().toggleClass("current"); 
});
like image 152
Juan Mendes Avatar answered Oct 01 '22 09:10

Juan Mendes


Here is a watered-down sample to show you the general technique.

$("#sh-zone-button-cart-menu").live("click", function(event)
{
    var that = this;

    $("#sh-zone-cart-menu").toggle(0, function(){
        alert($(that).attr('id'));
        alert($(this).attr('id'));
    });

});
like image 22
Dutchie432 Avatar answered Oct 01 '22 11:10

Dutchie432


You can save a reference to this in a variable, so you can use it later.

$("#sh-zone-button-cart-menu").live("click", function(event)
{
    event.preventDefault();
    var that = this;
    $("#sh-zone-cart-menu").toggle(0, function(){
        if($(this).is(":visible")){
            $(this).siblings(".sh-zone-button-link-menu-content").hide();
            $("#sh-zone-button-cart-menu").parent().removeClass("current");
            //need to reference (this) for $("#sh-zone-button-cart-menu") here
            $(that).show(); // <= "that" is sh-zone-button-cart-menu
        }               
    });
    $("#sh-zone-button-cart-menu").parent().toggleClass("current"); 
});
like image 24
Rocket Hazmat Avatar answered Oct 01 '22 10:10

Rocket Hazmat