In Javascript/JQuery what is $. for? - javascript

I'm writing a utility file and I've gotten some examples from online and this a form of writing the utility I've come across:
$.util = $.extend($.util || {}, {
//functions here...
});
and so I think I understand what it's doing. It allows me to call $.util.function() somewhere else, however when I remove the . in front of the $ the code breaks. What does this notation mean? What's the difference between $. and $?

$.util = something means "assign something to property util of object $".
$util = something means "assign something to variable $util"
Similarly, $.extend is "get value of property extend of object $" (which is a function in this exact scenario) and $extend is "get value of variable $extend"

If you're using jQuery, $ is just a variable contaning the jQuery object. So by writing $., you're essentially accessing jQuery properties and functions. Instead of $, you could also write jQuery and it should work the same way.
There's no special meaning to the $ character in JavaScript other than that. It acts like any other character, so $util is just a variable name.

jQuery is an object that is assigned to both jQuery and $ on the window
It has methods that act on collections of elements eg $('.some-element').someMethod() and static methods that are just attached to the jQuery object but don't modify a collection, They are just normal function attached to the jQuery object to prevent exposing too many functions to the global context.

$. - allows you to proceed to $ (jQuery) object property or method directly
$ - usually used as shortcut for invoking jQuery object
Whilst prefixing anything with $ won't make it jQueryable bec. this character can be used in variable name along with others (e.g. what is not applicable for PHP).

Consider jQuery as a big class woth a lot of static functions and constructs.
The right way for calling any of its functions should be jQuery.someFunc() for static functions and var obj = jQuery('css selectors') for creating an object for HTML objects and then executing functions on that object.
Now for easier coding, jQuery added $ as an alias for jQuery. It's nothing more than an alias.

Try this code:
<script type="text/javascript">
document.write('(jQuery === $) is ' + (jQuery === $) + '<br />');
document.write('typeof(jQuery) = ' + typeof(jQuery) + '<br />');
</script>
You will see:
(jQuery === $) is true
typeof(jQuery) = function
So jQuery is a function with a bunch of extra properties and functions attached to it.
If you're coming from a strongly-typed language background, the concept of attaching properties and methods to a function might seem strange, but you can do it in javascript.

Related

jQuery / JavaScript, why do I need to wrap variables in $() to use them?

Say I have a map on an array of elements. The callback function takes the index and the value at that position in the array.
If I wrap the array element that the callback receives in $(), it behaves as I expect. If I use it without wrapping it in $(), it gives an error.
var nonHiddenElements = $( "form :input" ).not(':hidden');
nonHiddenElements.map(function(index, element){
input_id = $(element).attr('id'); // this works
input_id = element.attr('id') ; // this gives an error
})
Can someone explain how this works.
Is this a jQuery quirk, or a JavScript thing?
What type of objects does my nonHiddenElements array contain exactly?
What is element that gets passed to the callback?
And mainly what is the $() doing?
You need to understand how jQuery actually works. I will try to explain it briefly.
$ is nothing but a normal javascript function. jQuery === $, is just a function with a fancy name. This function does a lot of different things, depending on what you pass in it. For example if you pass a string it will be treated as CSS selector and jQuery internals will try to find corresponding DOM elements. Or if you pass a string starting with < and ending with > jQuery will create a new DOM element by provided HTML string.
Now if you pass a DOM element or NodeCollection of DOM elements, it/they will be wrapped into jQuery instances so that they can have a jQuery prototype methods. There are many prototype methods jQuery offers. For example text, css, append, attr - those are all methods of jQuery prototype. They are defined basically like this (simplified):
jQuery.prototype.text = function() { ... }
Normal DOM elements don't have those convenient methods jQuery provides. And inside of methods like map or each if you check this value or element parameter like you do, you will see that they are actually not jQuery instances:
element instanceof jQuery // => false
and of course you can't use instance methods with not an instance.
So in order to use jQuery prototype methods you need have a jQuery instance, which you can obtain if you call jQuery function with DOM element passed in it:
$(element) instanceof jQuery // true
Javascript is a programming language.
jQuery is a JavaScript Library.
With jQuery:
$("some element")
In native JavaScript you would have to do something like this.
getElementById('elementByID')
Explained in detail here: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
MDN is a great resource for beginners. https://developer.mozilla.org/en-US/docs/Web/JavaScript

Why does this syntax of $ for jQuery and Backbone.js work?

For example, demo_view is an instance of Backbone.View, from this tutorial, this usage is recommended..
demo_view.$el.html()
As I understood, $ in jQuery is a function that should be used with parentheses, e.g. -> $("#id"), but why it can be used in demo_view.$el without a parentheses? Does anyone have ideas about this?
It's also a symbol which can be used to name a simple variable, it belongs to the set of allowed characters for naming variables in javascript.
In jQuery, $ is used to name a function (it's a shorthand for the variable jQuery actually) but they could have chosen any letter of the alphabet or any other valid variable name.
The reason why they use $el is to denote that the el element is a jquery object. It is purely for readability. Appending '$' before a variable identifier is kind of like a notation that denotes that the variable is a jquery object.
Both $ and _ are valid symbols that can be used in variable names and property names. The convention by some develoepers is to use $ to indicate that the property or variable is a jQuery object and not some ordinary object or value. Thus you can readily tell that it is a jQuery object and use jQuery methods without doubt.

What is the difference between a dollar sign and a dollar sign followed by a period in JQuery?

In jQuery, what is the difference between $ and $.? Please provide a practical explanation if possible.
$ is a reference (or synonym, if you want an analogy) to the global jQuery object. $.<method> calls a static method of the jQuery object, where $(<selector>) creates a new instance of the jQuery object.
In the context of jQuery, $ refers to the global jQuery object.
$. by itself is invalid JavaScript. As $ is an object, methods on this object are called like on any other object: $.methodname().
Maybe it becomes clearer by substituting $ with jQuery: jQuery.methodname().
I presume you are asking about the syntactic difference between $('#selector'); and $.parseJSON(str);.
The former is an invocation of a function called $ and the latter invokes it's method called parseJSON. Yup, functions can have methods - it is possible because Javascript functions are also objects. Figuratively speaking:
<script type="text/javascript">
function $(str) {
alert(str);
}
$.parseJSON = function () {
alert('Parsing JSON');
}
$('Hi');
$.parseJSON('{}');
</script>
From http://en.wikipedia.org/wiki/JQuery:
the $ function, which is a factory
method for the jQuery object. These
functions, often called commands, are
chainable; they each return a jQuery
object
$.-prefixed functions. These are
utility functions which do not work on
the jQuery object per se.
Typically, access to and manipulation
of multiple DOM nodes begins with the
$ function being called with a CSS
selector string, which results in a
jQuery object referencing matching
elements in the HTML page. This node
set can be manipulated by calling
instance methods on the jQuery object,
or on the nodes themselves. For
example:
$("div.test").add("p.quote").addClass("blue").slideDown("slow");
This line finds the union of all div
tags with class attribute test and all
p tags with CSS class attribute quote,
adds the class attribute blue to each
matched element, and then slides them
down with an animation. The $ and add
functions affect the matched set,
while the addClass and slideDown
affect the referenced nodes.
The methods prefixed with $. are
convenience methods or affect global
properties and behaviour. For example,
the following is an example of the map
function called each in jQuery:
$.each([1,2,3], function(){
document.write(this + 1); });
This writes the number 234 to the
document.
$ - dollar sign is also same as Jquery usage. But I preferred to use dollar sign because I like the way dollar sign is.

A few questions about JavaScript basics - $, "is not a function"

Being fully self-taught without actually reading up on JavaScript (It's my job now, believe it or not) there are a few things I accept but don't understand.
The first one is the dollar sign.
As far as I use understand it, it's a shortcut to document.getElementById(),
but if I log $ and document.getElementById() to console - Only $ returns a value. This value however is always function(), shouldn't it be. The element? What gives?
The second issue I have is something that keeps coming up in my code and I go out of my way to change the code to eliminate it. It's the "... is not a function" error.
For example:
if ($.inArray($(div_id).val(), arr) >= 0);
Will give the error .val() is not a function. Why? And how do I use the value of div_id to see if it's in array?
Hiya. When you're using Jquery (which I assume you are), then $ will return the jquery object. This can contain an array of matched HTML elements depending on the selector you used. For example $("#foo") will return the jquery object containing the element with id foo. You can get the actual HTML DOM element out using $("#foo")[0] - using the array-style notation.
Can you give us some more info on what you're trying to achieve with the $.inArray example?
$ is a valid variable name.
So if you try to use $ without setting it, it will not work.
A lot of people/frameworks however use $ as a shortcut to document.getElementById, they would declare it at the top of the script as:
function $(id) { return document.getElementById(id); }
$ and document.getElementById is not one of the same thing. $ gives you a function in console only when you are using some library like jquery which mapes $ to a function.
.val id primarly used to get value of the form elements and that is a jquery function. I think you need to learn more around javascript and jQuery
Neither Javascript nor the DOM define $, which (as other answerers said) is often defined in general-purpose DOM libraries like jQuery, Prototype or Mootools. Based on the particular code you included, I suspect you've been coding against the jQuery API (because you use $.inArray, see http://api.jquery.com/jQuery.inArray/; though your claim that $ aliases document.getElementById confuses matters, as jQuery expects CSS selectors rather than element IDs).
When $ is expected but undefined, that usually means you'll need to include the library whose API you're using in the HTML document.

Defining variables in jQuery

Can someone explain the difference between using a $ when defining variables in jQuery and not. Does it have any impact on performance?
var $someVar = $("a");
var someVar = $("a");
Also, what is the difference in calling variables with and without $(someVar) For example:
$(someVar).html();
someVar.html();
In your first snippet, there is no difference between those two. It's just a "notification" that this variable is holding a wrappet set of jQuery objects, which is commonly used by some developers.
In your second snippet you are actually doing two different things. You are wrapping someVar into a jQuery object and then access a jQuery method (html()).
In this example someVar could contain a DOM element or a selector string like "#some_element_id".
The other line assumes that someVar already IS a jQuery object, otherwise this call would fail.
There is no performance difference, it's just an identifier. $foo is often used to refer to jquery objects by experienced authors so as to not confuse them with non-jquery objects in complex scripts.
As for the $() wrapping, you can reference a DOMElement and wrap it in jQuery, eg
var e = document.body; $(e).hide()
If we tried e.hide() there would be no defined method as the body element doesn't have that method, it's only provided by the jQuery prototype chain.
$somevar and somevar are both the same . It is a convention to use a $ before a jquery variale so that you know that it is a jquery wrapped object .
( btw, $ were introduced in javascript to distinguish machine generated code for human written code )
However , $(somevar) and somevar are completely different .
$(somevar) -> You are calling the Jquery function and passing it somevar . You can also read this as Jquery(somevar) . So if somevar is referring to a dom id , the dom object would be wrapped by jquery and returned .

Categories