Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remembering what $(this) is

I have the following script which changes a jquery made object's color to blue:

$(".objects_list").live('click', function(event)
{
    $(this).css("color", "blue");
});

How do I remember what $(this) is so I can change the color again but from a different function or from an event of a different object?

like image 986
oshirowanen Avatar asked Dec 28 '22 02:12

oshirowanen


1 Answers

Instead of a global variable, you can use jQuery's data() method to associate information with the document itself:

$(".objects_list").live('click', function(event) {
    $(this).css("color", "blue");
    $(document).data("yourObjectKey", $(this));
});

Then you can easily get that information later:

$("otherSelector").click(function() {
    var yourObject = $(document).data("yourObjectKey");
    if (yourObject != null) {
        yourObject.css("color", "red");
    }
});

EDIT: If the element is destroyed and recreated between the two events, that method won't work. In that case, you can store the element's id instead of a reference to the element itself:

$(".objects_list").live('click', function(event) {
    $(this).css("color", "blue");
    $(document).data("yourObjectKey", this.id);
});

Then:

$("otherSelector").click(function() {
    var yourObjectId = $(document).data("yourObjectKey");
    if (yourObjectId != null) {
        $("#" + yourObjectId).css("color", "red");
    }
});
like image 172
Frédéric Hamidi Avatar answered Jan 05 '23 03:01

Frédéric Hamidi