Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why/how is everything $() based in jQuery?

I know a bit of JavaScript, and can work fine with jQuery. I just don't get why everything is referenced from $(). My understanding is that $ is never needed in JavaScript (unlike for example PHP, where every variable is prefixed with $).

I've looked through the source code, and it doesn't really make sense. Is it just that $ is the function name (for example, it could have easily have been jQuery(), but they selected $?) I assume not, though, as I don't think $ is valid in function names in JavaScript?

like image 748
apacheatyou Avatar asked Nov 02 '09 05:11

apacheatyou


People also ask

What does $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.

What is the main function of jQuery?

The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.

What is $() in JavaScript?

$() The $() function is shorthand for the getElementByID method, which, as noted above, returns the ID of a specific element of an HTML DOM. It's frequently used for manipulating elements in a document. $() allows for shorter and more efficient JavaScript coding. Traditional method: document.

Should I use jQuery or JavaScript?

Though JavaScript is the basic language from which jQuery has evolved, jQuery makes event handling, DOM manipulation, Ajax calls much easier than JavaScript. jQuery also allows us to add animated effects on our web page which takes a lot of pain and lines of code with JavaScript.


2 Answers

$ is just a global variable that's also a reference to the jQuery function, it's $ on purpose so it's less to type. $ is perfectly valid for a function name in ECMAScript:

function $(){}; alert(typeof $); 

Note that if you're using multiple libraries you can use function scope to avoid clashing dollar sign variables, eg:

jQuery.noConflict();
(function($){ 
    $('body').hide();
})(jQuery);
like image 104
meder omuraliev Avatar answered Oct 01 '22 07:10

meder omuraliev


$() is the same as jQuery(). Also, $ is a valid function name.

like image 23
JP Silvashy Avatar answered Oct 01 '22 08:10

JP Silvashy