Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use "$" in javascript/jQuery

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.

like image 573
Mark Kramer Avatar asked Sep 30 '11 01:09

Mark Kramer


People also ask

When should I use jQuery and 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.

What does $() short and stand for in jQuery?

$ is a short form of jQuery function. $() = jQuery() = window. $() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements.

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.

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.


3 Answers

$(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.

like image 86
James Khoury Avatar answered Nov 04 '22 18:11

James Khoury


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.

like image 28
jfriend00 Avatar answered Nov 04 '22 20:11

jfriend00


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

like image 31
Paradigm in Entropy Avatar answered Nov 04 '22 19:11

Paradigm in Entropy