I was wondering if someone could explain the difference in caching elements in JQuery. One with the dollar symbol and one without.
Here is an example:
var cached = $('.someElement');
var $cached = $('.someElement');
There is no difference. Both are cached, only the name of the variable is different.
Both cached
and $cached
are valid Javascript variables:
var $message = 'Hello';
var message = 'Hello';
The $variable syntax is just often used to indicate the variable contains a jQuery object, not another type (string, integer, DOM Element, ...). It's a kind of Hungarian notation, but it's just a convention amongst programmers. Nothing Javascript or jQuery imposes.
When people talk about caching a jQuery variable, they mean only doing the lookup once:
//Like this: cached: search is done once.
var clientSpan = $('#client');
clientSpan.hide();
clientSpan.show();
// ...
//Not like this: uncached
$('#client').hide();
$('#client').show();
// ...
The $
prefix is used to denote that the variable contains a jQuery object. In terms of code there is no difference, both elements in your example are now contained in a jQuery object, inside each variable.
For example:
var myVariable = $("#myElement").text(); // string
var $myVariable = $("#myElement"); // jQuery object