$ symbol in jQuery (and in javascript)

Before discussing about the functionality of ‘$’ in jQuery, let us take a look at what it( $ sign) means with respect to JavaScript, as a language.
With respect to javaScript, $ symbol is just a valid identifier.

Consider the following code snippet

$ = 5;
console.log($);

The above code snippet would just print number 5 in the console. So, from the perspective of javascript(as a language), $ symbol is just an identifier.

jQuery is a JavaScript library – particularly useful for DOM manipulation. jQuery uses this identifier to refer to the jQuery function, which is overloaded in many ways – including for getting the element by its id.

Consider the following HTML – it’s a simple HTML with a paragraph tag in its body.

Now, I just want to add text content to this paragraph using jQuery.
Below line of code would do the same.

jQuery("#paragraph1").text("This came from jQuery");

The above line contains couple of functions – jQuery and text

jQuery is for getting the element passed on the passed selector information – we are passing id of the element.
text – This function is used to set the content for the element.

Once you add the above line of jQuery code in ‘dollar.js’ and browse the html file, you can get the text “This came from jQuery” in the browser window.

Now, let us change that line to below

$("#paragraph1").text("This came from jQuery");

There will be no difference in the functionality as $ symbol is just a shorthand for jQuery function when using jQuery.

What if you want to use $ sign just as an identifier?

Let’s assume you have written lot of javascript code using $ as an identifier presuming you might not use jQuery or you are using a third party javascript library where $ is used as an identifier. Due to some project requirements, you have been asked to use jQuery – which in turn gives new meaning for $ symbol in your javascript code.

There are couple of options

1. Change your code to use new identifier instead of ‘$’ symbol
2. Instruct jQuery to use some other identifier to play the role of shorthand for ‘jQuery’ function in jQuery.

As first option is time consuming and may not be possible in some cases (where $ symbol is used in some 3rd party libraries), it is wise to go with second option.

 jQuery.noConflict()

will relinquish $ symbol for being the shorthand for jQuery and return the jQuery reference which you can use it.

var new$ = jQuery.noConflict();
new$("#paragraph1").text("This came from jQuery");
var $ = 5;
console.log($);

This identifier ‘new$’ will act as shorthand for jQuery which you can use it as you were using $ and the $ symbol will act just like a javascript variable.

Let’s say you are trying to use the $ function as you have used before and you are trying to update the text with the following code.

$("#paragraph1").text("This came from jQuery");

You’ll get “$ is not a function” error – as the significance of $ has been redefined.

 


Posted

in

by

Tags: