Jonathan E. Landrum
Jonathan E. Landrum

Reputation: 3172

Why Create jQuery Object Variables?

I see a lot of jQuery examples that do something like

var $element = $('#element');
$element.foo...

rather than just typing

$('#element').foo...

and I do realize there is a small bit of typing saved if you are working with $element a lot, but what about those times that $element is only called once or twice? Why do some developers declare it as a jQuery object variable in those instances? Is it also more efficient for the browser to process?

Upvotes: 3

Views: 3658

Answers (2)

Michał Staniewski
Michał Staniewski

Reputation: 260

It prevents from overwriting variable from another script

Upvotes: -3

Travis J
Travis J

Reputation: 82287

Usually this is done to avoid either re-wrapping an element or re-querying the page for the selector.

Such as in a click event

$('.className').click(function(){
 var $this = $(this);
 callSomeHelper($this);
 $this.hide();
 if( $this.data("placement") == "somePlacement" ){
  //some logic
 }
});

The real saver is when it is referencing a set of elements.

var $allSides = $('.side');

And now back in the click event, you can reference this without having to re-query

$('.top').click(function(){
   var door = $allSides.find(':visible');
});

There are obviously more in depth examples, but these two are the main cases that the variable is stored.

Upvotes: 10

Related Questions