When, if ever, should you use `jQuery` over `$`? - javascript

I was looking through some code and noticed:
button: function(e) {
e.preventDefault();
var $target = jQuery(e.target);
var link = $target.attr('href');
I was just a little unclear about the line var $target = jQuery(e.target);.
Why use jQuery here?

Usually you would like to use jQuery instead of $, when the latter conflicts with a globar variable from another library.
For instance, see this list: What JavaScript libraries are known to use the global dollar sign: window.$?
In that case, jQuery provides the noConflict() method, which:
Relinquish jQuery's control of the $ variable.
The documentation also states:
In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them.

Related

jQuery's dollar syntax vs dollar sign JavaScript "convention"

I've read here that for JavaScript there's a "convention" that the $ function be defined as a shortcut for document.getElementById, so I've defined the following function in a <script>,
function $(x) { return document.getElementById(x); }
so I could write $('main') instead of document.getElementById('main'), for instance.
Soon after, when I started looking into jQuery, I found that jQuery uses the syntax $(selector).action() extensively.
However, the two solutions don't seem to work nicely together.
Are indeed the two mutually exclusive? As in, if I use jQuery, I can't use the $ function above, and if I use the latter I can't use jQuery?
You can use jQuery.noConflict to return control of $. Then, to use jQuery, use jQuery instead of $.
jQuery.noConflict();
jQuery('#main')
You can also assign the returned value of noConflict to an object, and use it just like $:
var a = jQuery.noConflict();
a('#main')

What is difference between $(document) and $('*') and how to make sure $ reference is assigned to which library?

I understand it as: $(document) will have whole DOM of the current page like document, while $('*') also selects whole DOM, then what's the difference between them, aren't they are same ?
Will not $ assignment of different libraries will conflict, how they are assigned ?
$ in jQuery is basically Syntatic Sugar which means developers love to assign $ as shorthand for different library. In this case $ is shorthand of jQuery or window.jQuery.
jQuery can be run in compatibility mode if another library is already using $. Just use jQuery.noConflict(); to know if there is. $ is pretty commonly used as a selector function in various JavaScript libraries.
Run jQuery.noConflict() method to give control of the $ variable back to whichever library first implemented it. This helps to make sure that jQuery doesn't conflict with the $ object of other libraries.
Here is simple way of avoiding any conflict:
// Import other Library
// Import jQuery Library
$.noConflict();
// Code that uses other library's $ can follow here.
This technique is especially effective in conjunction with the .ready() method's ability to alias the jQuery object, as within the .ready() we can use $ if we wish without fear of conflicts later:
// Import other library
// Import jQuery
$.noConflict();
jQuery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.
As per jQuery documentation:
By default, jQuery uses "$" as shortcut for "jQuery"
having said that.
$(".class_name") or jQuery(".class_name") is the same.
Coming to next part of your question:
What is document ?
document is a Javascript internal DOM Object of the current webpage. In browser console you can go and invoke following:
document
It will return you whole DOM of page in Tree format.
> typeof(document)
<. object
So, typeof(document) returned object. Hence, document is a DOM object containing whole webpage sourcecode + many additional information in tree format.
What is $(document) ?
Similarly, $(document) is also an Object, in Array format having document and context of webpage.
What is $('*')?
It is also an object returned after jQuery process full DOM. It contains array of all the elements in the DOM so that jQuery can process it faster and return result
You can try in browser console.
> $('*')
> typeof($('*'))
$(document) - the document object as in window.document, parsed for jQuery;
$('*') - an array that contains all the objects (tags) in the DOM, since '*' is a general selector for everything.
$(document) will bring the object document which will contain the elements within it.
Where as $('*') will return an array of all elements

Can we replace $ in prototype.js with some thing else like $p or $proto

I am using jquery and prototype.js. There is conflict in $.It could be resolved by using var $j = jQuery.noConflict(), but i have a plenty of file that are using $ for jquery so that would not be easy to remove. even i am using some plugings that also needs to be rename.(like jquery.dataTables.bootstrap.js in which i have to change from $ to $j)
So my question is can we rename $ in prototype.js to something else, so it will be easy.I am using prototype of version 1.5.1.
Thanks
Simple answer, no - the some of the PrototypeJS modules (Array, Enumerable, RegExp, String, etc) depend on the $() function being available, and expect it to return an extended element instead of a jQuery collection.
However you can wrap the jQuery code in a immediately executed function to work around your problem.
for example
(function($){
//jQuery code in here that uses $()
})(jQuery);
This is basically a Javascript closure that renames the jQuery() method to $() inside that context
changing $ to $p causing some problem(like calling jquery hide or show function, prototype.js function gets called). So i what did to solve the conflict is to open a prototype.js related things in new tab and using jquery.noConflict().

Changing the name 'jQuery' to something else in jquery's source code

Is it possible to change the name 'jQuery' in jquery's source code to something else.
I want to perform my jQuery operations with this new name.
eg:
jQuery('#something').attr(); to
myName('#something').attr();
How do I do this?
var myName = jQuery.noConflict(true);
This will restore both $ and jQuery to whatever value (possibly undefined) they had before and assign the jQuery object to myName.
However, consider wrapping your code using jQuery in a closure where $ points to the jQuery object:
(function($) {
$('#something').something();
})(jQuery.noConflict(true));
People who work with your code expect $ to be used and will most likely be annoyed if they have to use something else; especially if it's something longer!
If you do not need to remove $ and jQuery, do not use jQuery.noConflict(true) but simply write jQuery at the places where I used jQuery.noConflict(true).
Also remember that no jQuery plugins will work if you remove the global jQuery before loading them (doing so after they are loaded is fine if they have been written properly, i.e. with the closure I suggested to you)
var $j = jQuery.noConflict();
// Use jQuery via $j(...)
$j(document).ready(function(){
$j("div").hide();
});

What is the meaning of "$" sign in JavaScript

In the following JavaScript code there is a dollar ($) sign. What does it mean?
$(window).bind('load', function() {
$('img.protect').protectImage();
});
Your snippet of code looks like it's referencing methods from one of the popular JavaScript libraries (jQuery, ProtoType, mooTools, and so on).
There's nothing mysterious about the use of $ in JavaScript. $ is simply a valid JavaScript identifier. JavaScript allows upper- and lower-case letters (in a wide variety of scripts, not just English), numbers (but not at the first character), $, _, and others.¹
Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it. In that case you use jQuery instead of $. In fact, $ is just a shortcut for jQuery.
¹ For the first character of an identifier, JavaScript allows "...any Unicode code point with the Unicode property “ID_Start”..." plus $ and _; details in the specification. For subsequent characters in an identifier, it allows anything with ID_Continue (which includes _) and $ (and a couple of control characters for historical compatibility).
From another answer:
A little history
Remember, there is nothing inherently special about $. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing document.getElementById. Should I capital 'b' of 'by'? Should I capital 'i' of Id? You get the drift. Because functions are first-class citizens in JavaScript, you can always do this:
var $ = document.getElementById; //freedom from document.getElementById!
When Prototype library arrived, they named their function, which gets the DOM elements, as '$'. Almost all the JavaScript libraries copied this idea. Prototype also introduced a $$ function to select elements using CSS selector.
jQuery also adapted $ function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$' could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)
That is most likely jQuery code (more precisely, JavaScript using the jQuery library).
The $ represents the jQuery Function, and is actually a shorthand alias for jQuery. (Unlike in most languages, the $ symbol is not reserved, and may be used as a variable name.) It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM).
As all the other answers say; it can be almost anything but is usually "JQuery".
However, in ES6 it is a string interpolation operator in a template "literal" eg.
var s = "new" ; // you can put whatever you think appropriate here.
var s2 = `There are so many ${s} ideas these days !!` ; //back-ticks not quotes
console.log(s2) ;
result:
There are so many new ideas these days !!
The $() is the shorthand version of jQuery() used in the jQuery Library.
In addition to the above answers, $ has no special meaning in javascript,it is free to be used in object naming. In jQuery, it is simply used as an alias for the jQuery object and jQuery() function.
However, you may encounter situations where you want to use it in conjunction with another JS library that also uses $, which would result a naming conflict. There is a method in JQuery just for this reason, jQuery.noConflict().
Here is a sample from jQuery doc's:
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
// Code that uses other library's $ can follow here.
</script>
Alternatively, you can also use a like this
(function ($) {
// Code in which we know exactly what the meaning of $ is
} (jQuery));
Ref:https://api.jquery.com/jquery.noconflict/
From the jQuery documentation describing the jQuery Core Object:
Many developers prefix a $ to the name of variables that contain jQuery
objects in order to help differentiate. There is nothing magic about
this practice – it just helps some people keep track of what different
variables contain.
Basic syntax is: $(selector).action()
A dollar sign to define jQuery A (selector) to "query (or find)" HTML elements A jQuery action() to be performed on the element(s)

Categories

Resources