Symbolwdd Symbolwdd - 4 years ago 73
Javascript Question

jQuery: Can't we assign jQuery(this) to a variable?

I am just practicing jQuery. So pardon me if this is a weird question.

Question: Can't we assign jQuery(this) to a variable?

Explanation:
I can assign various jQuery selectors to variables and then I can use those variables to call different jQuery functions.

For example

$filterSwitch = jQuery('.filter-switch');

$filterSwitch.click(function(e) {
alert("Filter Button Clicked"); // This works without any problem
});


On the other hand, I can't seem to use jQuery(this) after assigning it to a variable.
For Example

$filterSwitch = jQuery('.filter-switch');
$current = jQuery(this);

$filterSwitch.click(function(e) {
$current.toggleClass("filter-on"); // This does not work
jQuery(this).toggleClass("filter-on"); // This works
});


Is this not allowed or is there any specific way to assign jQuey(this) to a variable?

Answer Source

That is because you need to remember that this refers to the context you are currently in.

So the first

$current = jQuery(this); 

Could mean the body or something other than the second this.

The second this is in the context of the click method, and that context is set to .filter-switch

Hope that makes any sense :)

You can do this:

$filterSwitch = jQuery('.filter-switch');

$filterSwitch.click(function(e) {
   $filterSwitch.toggleClass("filter-on"); // This works for all elements with that class
   jQuery(this).toggleClass("filter-on"); // This works only for the one you're clicking atm
});

Just be aware that the first line, now refers to all elements that have the filter-switch class, and the second line only refers to the one you're handing at the moment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download