Magic

So what is going on when we use the magical $() ?

I’ve broken it up so you can read it carefully.

‘$’ is a function. When you type ‘$()’ , you are calling a function. The jQuery ‘$()’ function returns an object. That returned object contains all the jQuery methods like ‘.hide()’, ‘.load()’ and so on, all the functions we use jQuery for. So when you call .hide(), you are calling a method inside an object, the object that the original jQuery function returned. Guess what .hide() returns after you call it? Again, it returns the same object with all the jQuery methods. So each time you chain a jQuery method on the end, every method returns the same object full of the same jQuery methods for you to use.

Lets explore how it works with some simple examples.

Use this jsbin, and update the code as we go along.

In the below example we have an object with methods (methods are just functions inside objects). We can call the methods inside object by saying ‘objectName.methodName()’.

An object with very useful methods

But if we try to chain the methods like in jQuery we get an error, because each method call is not returning the object again for us to use the methods inside. Below we are calling .right() on nothing because .left() returns no object with methods inside.

method chaining fails!

The solution to this is as follows:

Within each method we return ‘this’. This refers to whatever object comes before the ‘.’ so in this context, the $ object. That is how we pass the object back to the user after each method is used.

So now we can endlessly chain functions off into the sunset! Our jQuery experience is almost complete. Now we need to find a way of actually targeting the webpage to modify something.

But if we try passing css selectors like this we’ll have problems:

To be able to pass in parameters ( such as CSS selectors ) jQuery-style we need our iconic $ object to actually be a function that takes parameters.

Here we can see that the usage has changed slightly. $ is now a function but still returns the same object as before, so the chained methods don’t know the difference, and you can use it like jQuery — pass the initial function some information (eg. a string like ”.list .best-item”), then chain on the methods.

So now lets make our $ function grab some webpage elements and save them so the chained methods can use them.

Here we creating an object called state with two fields. nodeList contains a nodeList, surprisingly, based on the css selectors you passed into $(here).

Dom contains the same dom nodes as nodeList, but coerced into an array, so we can use Array methods on it like forEach.

( You don’t need to save the dom array inside a state object along with a nodeList, you can just directly save dom there instead, but I think it’s fun to keep the original nodeList around as well for the sake of learning. )