Ive been starting to do javascript and jQuery recently and one thing I constantly find myself wondering is when to use "$" I know that indicates jQuery but it just doesn't always seem to be that way. I'll give some examples:
These are two scripts I've written:
First:
$(function() {
var newHTML = '<span style="font-size: 1.7em; text-align:center; line-height:50px;">Login</span>';
var oldHTML = '<span style="font-size: 32px; line-height: 18px;">+</span><span style="font-size: 14px; float: left;">Add to watchlist</span>';
// on mouse over
$("a.bid-addwatchlist").hover(
function () {
(this).innerHTML = newHTML;
},
// on mouse out
function () {
(this).innerHTML = oldHTML;
});
});
Second:
(function(){
$("#container a").click(function(){
if ($(this).html() == "Stop Listening")
{
$(this).html("Listen");
}
else if ($(this).html() == "Listen")
{
$(this).html("Stop Listening");
}
});
});
Why is it that in the first script it wouldn't work if I had a $ before "this" but the second script needed it?
Note: I did already look here: When to use $ and when not to
But that answer was not nearly comprehensive enough.
Ive been starting to do javascript and jQuery recently and one thing I constantly find myself wondering is when to use "$" I know that indicates jQuery but it just doesn't always seem to be that way. I'll give some examples:
These are two scripts I've written:
First:
$(function() {
var newHTML = '<span style="font-size: 1.7em; text-align:center; line-height:50px;">Login</span>';
var oldHTML = '<span style="font-size: 32px; line-height: 18px;">+</span><span style="font-size: 14px; float: left;">Add to watchlist</span>';
// on mouse over
$("a.bid-addwatchlist").hover(
function () {
(this).innerHTML = newHTML;
},
// on mouse out
function () {
(this).innerHTML = oldHTML;
});
});
Second:
(function(){
$("#container a").click(function(){
if ($(this).html() == "Stop Listening")
{
$(this).html("Listen");
}
else if ($(this).html() == "Listen")
{
$(this).html("Stop Listening");
}
});
});
Why is it that in the first script it wouldn't work if I had a $ before "this" but the second script needed it?
Note: I did already look here: When to use $ and when not to
But that answer was not nearly comprehensive enough.
Share Improve this question edited May 23, 2017 at 12:03 CommunityBot 11 silver badge asked Sep 30, 2011 at 1:58 Mark KramerMark Kramer 3,2147 gold badges37 silver badges53 bronze badges 2- 1 docs.jquery.com/How_jQuery_Works – Jack Commented Sep 30, 2011 at 2:01
- Note that $ is just an identifier, it only references jQuery if you've loaded the jQuery library (or assigned it a reference to jQuery some other way). – RobG Commented Sep 30, 2011 at 2:49
5 Answers
Reset to default 11$(function(){
// ...
});
is equivalent to:
$(document).ready(function () {
// ...
});
This is because jQuery itself will execute the function on the ready event.
On the other hand the below creates an anonymous function that isn't executed:
(function(){
// ...
});
What you'd need instead is:
(function(){
// ...
})();
and that would execute the function immediately.
The first script doesn't actually need the $(this)
unless you want to use jQuery functions as the second function one does.
Although it is good to note that the second function isn't executed as stated above unless you have other code that isn't shown here.
You use $ when you NEED a jQuery object or method in order to solve your problem. If you have a DOM element already and a direct DOM property will give you everything you need, then there's no reason to use jQuery. On the other hand, if you want to use a jQuery method that is unique to jQuery, then, of course, you create a jQuery object and call a method on it.
Example:
$("#myButton").blur(function() {
if (!this.value) {
this.value = "Enter name";
}
});
So, in the first line of this script, we use a jQuery object because it's easier to find an object in the page and assign an event handler.
Inside the handler, I'm using plain javascript and direct properties because there's no advantage to using jQuery. This could have been written this way:
$("#myButton").blur(function() {
if (!$(this).val()) {
$(this).val("Enter name");
}
});
But, there's no advantage to using jQuery inside this handler. It's just more code and more function calls.
So ... use it when you need it or it makes more readable or more reliable code. If none of those apply, don't use jQuery for that particular operation.
JQuery objects are meant to represent a DOM element. In the second example, you are using "$(this)" followed by a function call. This means that you can use only the interfaces support by the JQuery object.
In the first example, you are just using "this", which is a reference to the DOM element that owns the current execution context. DOM elements do not implement the JQuery interface (or else you wouldn't need to use JQuery at all!)
In other words, JQuery maintains enough information about a DOM element to be able to find it and perform manipulations on it. However, that does not mean that JQuery exposes an interface identical to a DOM elements.
EDIT: DOM stands for Document Object Model. Essentially, this is a model where all elements in the document are represented as objects (DOM elements). For example, you could use document.getElementById("anId") to retrieve a "DOM element" by the value of its ID attribute. This Document Object Model gives us the ability to manipulate and alter various parts of the document via scripting languages. Basically, the DOM is just a bunch of hierarchical objects that represent the elements on your page. These objects expose interfaces like "innerHTML"--Since JQuery objects are not DOM objects, they do not
look at jquery source code
jQuery.fn = jQuery.prototype = {
....
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
....
}
$(handler) the handler will execute when DOM is loaded, if DOM already loaded, handler will execute immediately.
(handler) just declare an anonymous function, if you want to execute it you should use (handler)() as James Khoury's answer;
In the first case, this
is a DOM element on which the function is called. You're using the innerHtml property directly.
In the second case, you're wrapping the DOM element in a jQuery wrapper and using jQuery methods such as .html()
and you're therefore manipulating the element's innerHtml
indirectly.