Synopsys
All variables that are use to store/cache jQuery objects should have a name prefixed with a ‘$’.
Consider using chains in place of jQuery object variables.
Description
There is often a requirement to store/cache a jQuery selection in a holding variable. Where this is the case, you should prefix the variable name with a ‘$’.
For example:
var $MyTable = $("#MyTable"); $MyTable.addClass("MyTable"); $MyTable.append("<tr></tr>");
Also, in conjunction with $(this):
var $this = $(this);
Storing in a holding variable helps reduce the number of calls into jQuery, and enhances performance. The dollar notation on all jQuery-related variables helps us easily distinguish jQuery variables from standard JavaScript variables at a glance (e.g. string, integer, etc).
Cached Variables vs Chains
The above example could have been written efficiently as a chain like so:
$("#MyTable").addClass("MyTable").append("<tr></tr>");
This has the advantage in removing the need for a cached variable, and in this particular case makes sense.
When chains become long, complex and especially hard to read, you should split them up, storing intermediate selections in a holding variable: http://stackoverflow.com/questions/1286829/is-there-a-preferred-way-of-formatting-jquery-chains-to-make-them-more-readable
This does not result in much (if any) of a performance hit. Objects are held as references, not values, so their impact is minimal: http://stackoverflow.com/questions/1287106/can-it-be-disadvantageous-to-store-jquery-objects-in-a-variable
The Chaining Standards cover this in more detail.
jQuery Coding Standards Menu
[...] jQuery Variables [...]
[...] more: jQuery Standards (1) – jQuery Variables « James Wiseman If you enjoyed this article please consider sharing [...]
[...] here to see the original: jQuery Coding Standards (1) – jQuery Variables | James Wiseman If you enjoyed this article please consider sharing [...]
[...] jQuery Variables [...]
[...] jQuery Variables [...]
[...] jQuery Variables [...]
[...] jQuery Variables [...]
[...] jQuery Variables [...]