Skip to content Skip to sidebar Skip to footer

Access External Objects From Jquery Callback Functions

Scenario: My_Object = { my_div: '#mydiv', my_method: function() { $(this.my_div).fadeOut('slow', function() { $(this.my_div).fadeIn('slow'); }); } } 'this.my_div' i

Solution 1:

Store "this" in temporary variable:

My_Object = {

  my_div: "#mydiv",

  my_method: function()
  {
    var tmp = this;
    $(this.my_div).fadeOut("slow", function() { $(tmp.my_div).fadeIn("slow"); });
  }

}

Solution 2:

That's because inside the fadeOut() callback, this is now the element being faded out. I assume you want to fade it back in so just do this:

My_Object = {
  my_div: "#mydiv",
  my_method: function() {
    $(this.my_div).fadeOut("slow", function() {
      $(this).fadeIn("slow"); // refers to the same object being faded out
    });
  }
}

The Javascript this concept is a little confusing.

Post a Comment for "Access External Objects From Jquery Callback Functions"