Question

I'm trying to reference $(this) but jquery can't find it. Simple code:

$(".testBox").click(function(){
    $(this).addClass("backRed");
    $.get("/data/TESTer/?tickle=yes", function(data) {
        $(this).addClass("backGreen");
        alert("Data Loaded: " + data);
    });
});

In this scenario, the .testBox will get the class backRed, but will not get the class backGreen, probably because $(this) is now referencing something from the $.get. How can I reference the clicked $(this) within the $.get parameters?

Was it helpful?

Solution

The easy way is to create a closure like this:

$(".testBox").click(function(){
    var me = $(this);
    me.addClass("backRed");
    $.get("/data/TESTer/?tickle=yes", function(data) {
        me.addClass("backGreen");
        alert("Data Loaded: " + data);
    });
});

What this does is:

  • create a local scope variable that stores the $(this).
  • use that variable in the inner-function

What happens is that it will create a closure, a function that has a reference to an outer parent and can use variables from that parent.

OTHER TIPS

    $(".testBox").click(function(){
        var $this = $(this);
        $this.addClass("backRed");
        $.get("/data/TESTer/?tickle=yes", function(data) {
            $this.addClass("backGreen");
            alert("Data Loaded: " + data);
        });
    });

Easiest way is probably to do this:

$(".testBox").click(function(){
    var self = $(this);
    self.addClass("backRed");
    $.get("/data/TESTer/?tickle=yes", function(data) {
        self.addClass("backGreen");
        alert("Data Loaded: " + data);
    });
});

Cache the selector into $this

$(".testBox").click(function(){

    var $this = $(this);
    $this.addClass("backRed");
    $.get("/data/TESTer/?tickle=yes", function(data) {
        $this.addClass("backGreen");
        alert("Data Loaded: " + data);
    });
});

The $.ajax() method (from which $.get() is derived) has a context argument that is specifically meant to control the value of this in the success handler.

So, you could use that option:

$(".testBox").click(function(){
    $(this).addClass("backRed");
    $.ajax({
        url: "/data/TESTer/?tickle=yes",
        context: this, 
        success: function(data) {
            $(this).addClass("backGreen");
            alert("Data Loaded: " + data);
        }
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top