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.
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");
});
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'));
});
});
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");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With