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?
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");
}
});
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