Syom Syom - 8 months ago 51
Javascript Question

Why use $ in the name of javascript variables?

Possible Duplicates:

Why would a javascript variable start with a dollar sign?

JQuery : What is the difference between “var test” and “var $test”

What is the difference between this two ways of initializing variables?

var $val = 'something'


var val = 'something'

as I see they are the same thing.

Maybe in this case
is only the part of name in variable?
(it will become a meaningless question in that case:/)


Answer Source

The $ in the variable name is only part of the name, but the convention is to use it to start variable names when the variable represents a jQuery object.

var $myHeaderDiv = $('#header');
var myHeaderDiv = document.getElementById('header');

Now later in your code, you know the $myHeaderDiv is already a jQuery object, so you can call jQuery functions:


To get from the DOM-variable to the jQuery variable:

var $myHeaderDiv = jQuery(myHeaderDiv); //assign to another variable
jQuery(myHeaderDiv).fade(); //use directly

//or, as the $ is aliased to the jQuery object if you don't specify otherwise:
var $myHeaderDiv = jQuery(myHeaderDiv); //assign
$(myHeaderDiv).fade(); //use

To get from the jQuery variable to the DOM-variable.

var myHeaderDiv = $myHeaderDiv.get(0);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download