Monday, February 22, 2010

Beginning with jQuery - A Solid Foundation to Learn The Basics

It's been a while since my last article and I'm very pleased to come up with this one.

Enjoy.

Table of Contents



Introduction


Hi,

Why another "learn the basics of jQuery" article? Because I was told to do so ;) but more importantly, because I feel that there are some misunderstood concepts that programmers absolutely have to know if they want to do some serious web development.

The fact that the web is (supposedly) moving fast coupled with frameworks that tend to hide the reality makes web development for a newcomer difficult. But in reality, it shouldn't be if you understand the basics. Frameworks are trying to hide what's going on for you to be able to do web sites in "minutes". But after a while you realize that frameworks have shortcomings and that you must learn the basics to achieve what you wan to do. Welcome back to square one after wasted time.

jQuery's hype brings confusion and misconceptions


On this blog, I receive a tiny 500 visits a month and most of this traffic is coming from Google's search engine (You can't just say Google anymore, they do lots of other stuff these days ;)). This is where I realized that there was so much confusion about jQuery and web development in general. For example, I have people coming from Google with the following keywords:

  • "jquery sqlserver out of memory"
  • "mvc and google map = jquery"

Ok let's stop here. I took two examples, one involving the server and another involving another JavaScript library. Now you may or may not agree with me that if you truly want to know and master jQuery, you got to know where jQuery comes into play in the big HTTP/Web picture. And clearly, some concepts have been mixed up here. If you're a little lost too, don't worry.

Way Before the beginning of jQuery


Before the beginning of jQuery and lots of other stuff, there was the HTTP Protocol. Guess what, the HTTP protocol barely evolved since its beginning. If you don't understand the HTTP protocol you're pretty doomed if you want to do high quality web development. But the bright side is, it never changes...

Forget about the formal definitions of the HTTP protocol in Wikipedia, here's what you got to know: The HTTP protocol is composed of client and servers where clients are making requests to servers to get content from it:

clients are requesting files from web servers according to a network protocol

As you can see clients are only requesting files to the server and the servers are only serving content to clients.

There's nothing complicated here and there's no particular technology involved either. In fact, whether the client is a web browser or a telnet session, the server couldn't care less. On the other side, if the server is running Apache, the client doesn't care either. AS LONG AS BOTH ARE FOLLOWING THE HTTP PROTOCOL.

It's the separation between the two (what's going through the wires in the middle of the previous picture) that makes the whole thing transparent and working since 1990 even thought the technologies used on clients and servers evolved (Browsers versions, Coldfusion, ASP, PHP, Perl, etc).

How browsers internally represents the HTML content


We can now toss the server portion out of the way since it only serves content. Let's focus our attention to a specific type of client, the browser.

As we saw earlier, the browser only request some content from the server and process it:

the html in text format received from the server is read by the browser

As human we usually represents concepts with something readable by us like text and symbols and HTML is only another example: we represent web pages with a markup language (HTML). But for machines, parsing text can be a tedious task. To be more efficient, browsers are parsing HTML pages only once after receiving the response from the server. They then transform the text representation of the web page into a data structure in the form of a tree called the DOM (document object model). That way they can also validate the document and have a more flexible rendering engine.

from the html received, the browser constructs the document object model

A very very important thing to know is that if the source document contains logical errors (The HTML document is not standard compliant), nobody knows how the DOM will be constructed. Internet Explorer will react differently than Chrome when encountering errors because the standard doesn't define error handling guidelines. Afterwards, you could have surprises using JavaScript or jQuery to manipulate the DOM as it may be different from one browser to another.

As a side note, when you do a "view page source" in your favorite browser, it only shows you the original text it downloaded from the server earlier and not what's in memory! That's why if you've manipulated the DOM with JavaScript and then do a "view source" you won't see the changes. But more on that later.

Dynamically changing the page's content (DOM)


It's possible to manipulate the DOM with a client side language called JavaScript. JavaScript can manipulate the properties and the elements of the DOM as soon as the page is loading and afterwards on events triggered by the user. The source of the image could be changed for example:

javascript is a programming language and is a collection of functions and objects to manipulate the dom

Sounds good isn't it? No. The problem is that JavaScript functions and capabilities are implemented differently across browsers vendors. For example, a function to do something could be named differently in two different browsers. How can that be? This is another story.. but for now, your scripts must take this into account and it can be a real pain.

A Special case with AJAX


Before hitting jQuery, I feel that now is the proper time to talk about AJAX. AJAX is nothing more than a standard HTTP request made to the server (see above, first image). AJAX doesn't bend the rules. It obeys to the same laws of the HTTP protocol. But normally, when the browser navigates to another page (or image, or text file), the current one is wiped out from memory and visually cleared to give its place to the new one we're navigating to. In AJAX, nothing is cleared out from memory and the current page stays there. That's the only difference. So, with AJAX, you can fetch new content from the server without losing the current DOM. The content retrieved is passed to the document as a JavaScript variable. You can then insert this new content into the DOM or do whatever it please you. So you see, there is almost no difference excepted: this is not the browser window that is handling the new content, this is you in JavaScript. That being said, let's finally look at jQuery.

Where jQuery is sitting in the big picture


To ease JavaScript development, several JavaScript libraries were created to encapsulate the native JavaScript functions and have a more uniform programming environment. That's also the case for jQuery. So we have all the knowledge now to know that jQuery is layer of abstraction above the native JavaScript functions of the browser:

jquery is a javascript library that eases the manipulation of the dom as opposed to the use of javascript alone

When I see this, two things comes to mind:

  1. jQuery can't do more things than JavaScript can actually do... right? Right. I know, it's a shocker.
    -and-
  2. Where the hell "jquery sqlserver out of memory" can be coming from?

The same thing applies to "mvc and google map = jquery". You can now understand that basic key concepts have been mixed up or never truly understood by those googlers. But fortunately, now you know why! (or already knew and thinking the pace of this article is horribly slow)

jQuery And Other Libraries


So jQuery provide a more uniform and easier way to manipulate the DOM. But nothing prevent you to access DOM elements yourself using natives JavaScript functions at the same time. Another amusing kind of keywords I encounter on my site is keywords like "jquery and google maps". People want to use jQuery everywhere, even with perfectly independent JavaScript libraries like Google Maps. That makes no sense. Again, I think it's just a misunderstanding. Independent libraries are not encapsulated by other independent libraries... they sit next to each other:

jquery can be used along with other libraries but rarely encapsulates them

Sure sometimes a function in jQuery could be helpful in another context, but that's different than trying to do everything in jQuery. It makes little sense to try to encapsulate a library that already encapsulates your native JavaScript functions.

jQuery Architecture


jQuery seems complicated at first but lets write ourselves a little library first and then look at the real deal. Our library will have two functions, a regular function to get a DOM element, and another static function to add two numbers:

function myLibrary(id) {
    return document.getElementById(id);
}

myLibrary.Add = function(a, b) {
    return a + b;
};

var myDiv = myLibrary('div1');
var sum = myLibrary.Add(1, 3);

We're pretty happy about our library but the function name is pretty long. What if we create an alias of the main function to make it shorter. Let's take the dollar sign ('$') which is nothing more in JavaScript than a 27th letter in the alphabet. The dollar sign is also more distinctive and less prone to name clashes:

var $ = myLibrary;      // let's make an alias of our library

var myDiv = $('div1');  // do the same as usual
var sum = $.Add(1, 3);

That's great! And guess what, with my previous examples you saw how jQuery was constructed (roughly). This is basically the same thing. If you were shy about the strange nature of the library, you should now be more comfortable with it.

To prove that jQuery is like our little library, here's something you can try. The jQuery's library defines a "jQuery" function and the dollar sign is an alias to it:

alert(jQuery);       // shows a function
alert($ == jQuery);  // shows true

There's two main parts in the jQuery's library (like ours), a selector function "$()" and static functions (called utility functions) "$.Xyz". You can see an examples of both in the next snippet (actual jQuery code):

var myDiv = $('#div1');
var trimmed = $.trim('  hello world ');

Selecting and Manipulating Elements with jQuery Selectors


Maybe you noticed a little difference between our library and jQuery. The parameter to the function that selects DOM elements are different:

var myLibDiv = myLibrary('div1');
var jQueryDiv = jQuery('#div1');

This is because jQuery is very flexible with the way you can select DOM elements with the jQuery selector function. You can query the DOM with other properties than object ids. Inspired by the CSS syntax, jQuery actually offer many ways to match objects in a document:

jQuery('#id');        // Match objects by id
jQuery('.class');     // Match objects by CSS class
jQuery('#id1, #id2'); // Match objects having id1 or id2
[...]

See Selectors in the jQuery documentation to learn many other ways to match and retrieve DOM elements from a document.

There's another difference between our library and jQuery. Our library can only find one element at a time (by its id) while jQuery can match multiple elements in a single selector function call:

// returns a single element having the id 'mainTitle'
var title = myLibrary('mainTitle');
// returns every element having the class 'title'
var titles = jQuery('.title');

As opposed to our little library, what is returned by the jQuery selector function is not the real DOM objects. They are encapsulated by another jQuery object. So if we take this example again:

var myvar = jQuery('.title');

Visually, it would appear like this:

the dom objects found when using the selector are put in a jquery object

So what are the benefits? Remember that every JavaScript implementations across browsers are a little different. If the jQuery selector were to return DOM objects, it would have little value as you would have to manipulate those objects just like before. After all, what's the purpose of selecting objects without manipulating them. And jQuery provide a standard way across browsers to do just that and this is where the real power of jQuery sits:

the object returned by the jquery selector exposes various functions that are acting on the dom objects

That's it, the jQuery object returned provide manipulation functions that acts on every DOM objects found! Here's an example that would hide every object with the class 'title':

var myvar = $('.title');
myvar.hide();

// Hint, the last two lines could be simplified as
$('.title').hide();

To know every function that you can apply on matched objects, please refer to the jQuery API documentation online.

One last thing before closing on this section. Each and every function like the 'hide' function we used previously are also returning a jQuery object containing the DOM elements just like the main jQuery selector function. This is really powerful:

// return a jQuery object containing DOM elements
var myvar = $('.title');
// returns also a jQuery object containing our DOM elements
var myvar2 = myvar.hide();
// same here
var myvar3 = myvar2.height(200);
// same here
var myvar4 = myvar3.show();

// Hint, the last lines could be simplified as
$('.title').hide().height(200).show();

The above snippet, even though pretty pointless, hides every titles to set their height to 200px before showing them again. The succession of function calls is called (no pun intended) chaining.

I guess you now have what it takes to fully understand jQuery selectors and manipulators. Let's move on to utilities functions.

jQuery utility functions


If you remember, our little library had a static 'Add' function:

myLibrary.Add = function(a, b) {
    return a + b;
};
var sum = myLibrary.Add(1, 3);

Just like that, jQuery provides a lot of useful functions to further encapsulate the native JavaScript functions of the browsers. Here's an example (we already saw the 'trim' function):

$.get('/index.html', function(data) {
    alert(data);
});

The 'get' function is making an ajax request to retrieve asynchronously some content from the server. Please refer to the section referring to AJAX earlier in this document if you forgot how AJAX is working.

There's plenty of utility functions in jQuery and I'll let yourself discover them. Here's a link or two dedicated to them in the jQuery documentation:


Conclusion


So here we are. We saw how jQuery was constructed and what it does. I didn't take the "let's do massive complex examples" because there are plenty of tutorials out there. I provided some links for you to get started doing real things.

I hope with this (hopefully) simple article, that you have a clearer picture of what's and what's not jQuery.

Next Steps


If you look at the comments below, some of you pointed out that I should write a book on jQuery! I can't thank you enough for all the comments but I feel like there are already many good things for you out there that you can get right away. But what I can do is this: I can personally recommend you the book . I've gone through this book myself and I think this is what you need after reading this article to get you to do amazing things with jQuery.

Another great book that I can recommend you is a plain JavaScript book called . This is THE book to have if you want to master the basics of JavaScript. Even today, I can open up the book at any page and learn or re-learn something useful. JavaScript is so rich, having an in-depth knowledge of it is the key to success to build great applications with any library.

Related Articles



See ya

48 comments:

Anonymous Avatar Anonymous said...

Nice explanation about $() function. Good job!

Unknown said...

Thank you very much!

According to another comment I'll also try to talk about the $(document).ready event which is also very widespread.

Thanks again

Anonymous Avatar Anonymous said...

Great explanation!This is what i really miss on any subject matter that i want to learn these days. The BASICS are already too complex and difficult to understand OR the basics are not there at all. There is a saying, GET THE BASICS RIGHT and YOU CAN DO ANYTHING. You have made a pretty good example of that!. This is what i call a real GURU who can explain the basics in a simple, easy way.

THANKS a lot.And keep up the good work!

Anonymous Avatar Anonymous said...

Excellent. Required reading for the jquery beginner.

Ngala T. said...

I think you should write a book .You are really good in clarifying a complex subject. Thanks once more for these fantastic post.

Anonymous Avatar Anonymous said...

" Each and every function like the 'hide' function we used previously are also returning a jQuery object containing the DOM elements"

Does the returned jquery contains a modified DOM or the original DOM?

Unknown said...

The jQuery object contains the same DOM objects as before, jQuery only modified their properties! Let me know if that helps.

Thanks for reading!

Unknown said...

In fact, the jQuery object returned contains references to DOM objects, not copies.

Just a clarification

Anonymous Avatar Anonymous said...

Really helpful. Thanks!

Anonymous Avatar Anonymous said...

nice article man!

Anonymous Avatar Anonymous said...

In the conclusion you state;

I didn't took the "let's do massive complex examples" because there are plenty of tutorials out there.

Instead of took, did you mean take?

Otherwise a superb article

Unknown said...

Yes sorry I'll fix that, don't hesitate to correct me again, my primary language is french.. nop, can't be perfect ;)

Anonymous Avatar Anonymous said...

Very nice man! Thanks!

Anonymous Avatar Anonymous said...

Hi Great article thanks.

However, you stated "That's why if you've manipulated the DOM with JavaScript and then do a "view source" you won't see the changes. But more on that later."

As far as i can tell there wasn't any return to this concept. I was hoping for a way to be able to view the effects of jquery in the source.

Thanks

Unknown said...

Hi,

You're right I didn't explained that well.

If you want to see the effects of jQuery in FireFox, download the developer toolbar and click on "View Source" then "View Generated Source".

I'll put it in the article later, I'm at work :)

Thanks for pointing that out!

Unknown said...

Or you can "Inspect" the document (with Firebug in FF or in Chrome directly)

Anonymous Avatar Anonymous said...

Great article Mike keep em' coming!

Anonymous Avatar Anonymous said...

Awesome post!

Anonymous Avatar Anonymous said...

I have avoided JQuery up to now, but after this really superior view of the basics, it doesn't look too intimidating.

Thanks, Mike. Be looking for a book!

Sicofonia said...

This article is just superb. I've been using jQuery very scarcely as I'm still unable to fully get a good grasp of the thing. Seeing where it comes from (thanks to your example) has answered a lot of questions I had.

Good job mate.

Anonymous Avatar Anonymous said...

Really nice

Anonymous Avatar Anonymous said...

Thanks Mike. That made a lot of sense. Very well put together!

Anonymous Avatar Anonymous said...

Nice, simple and to the point explanation of jQuery fundamentals.

I wish books were like that.

Anonymous Avatar Anonymous said...

Awesome post : )
Really liked the $ alias example!

Anonymous Avatar Anonymous said...

jQuery and the joy of $ conflicts would be a really good article to put together.

Anonymous Avatar Anonymous said...

Thanks for writing this article.
As a novice "programmer", it would be a lie for me to say that I understood everything, but the parts I did get really make sense now. Time to start checking out jQuery!

Anonymous Avatar Anonymous said...

Hahaha, now that you mention it here you'll get more hits from google like "jquery mysql out of memory" lol

Btw, i read the whole article and i liked it.

Karthikeyan said...

this was excellent. nothing compares to strong basics

Anonymous Avatar Anonymous said...

:) great article!
Great connection betweeen the topics!

Nice Articles its useful thanks...
http://www.raghibsuleman.com/

saiy2k said...

I been wondering a long time, how the jquery selectors worked...
thx a bunch for this article... it explained those very nicely :D

Jeff Shamley said...

as a jQuery newbie, this article was very helpful in my base understanding of the framework. thanks!

RAMESH PARAJULI said...

Simplified explanation of a great topic. Thanks!!!!

Anonymous Avatar Anonymous said...

Great Great Article.
Perfect for ppl who have no clue about javascript !

Maeik said...

Thank you very much, this was nicely written! I enjoyed the tone and humor!

I am into java middle tier development and was always afraid of front end jquery was like Rocket science for me :P but your explanation is awesome and gave enough confidence to me for exploring this library.Thanks a lot.

Anonymous Avatar Anonymous said...

Mike,

You taught me jquery in 10 minutes.
You made it so easy and highlighted basics which is what programming is all about. I think you are exceptional.
Thanks, Sunil

Unknown said...

Thank you Sunil for your comment it is really appreciated :)

MindWalker said...

thanks mike
I am a seasoned developer in many languages;

Looking at browser technology I know there is lot of hype going on out there,as I knew all along in other hot technology ares like ESB etc ,
but looking at your cool exposure style gives me a feel it is still worth getting into the field and do real stuff for real people.
Thanks for writing the jquery exposure.
BTW, I may point out ,the effects of jquery /or javascript can be seen ,while it is happening, by using jquey to write [update the contents of]a predefined textarea in the same dom! This would not require any debug tools to see the effect of jquery as it does the work.

Nivedita :) :) said...

Mike ...
The article was simply excellent ...
I am a newbie in a development ... but after your article i guess with a small exploration i wont be a newbie anymore ...

Regards
Nivedita

Rabin said...

Hi Mike,
Actually I got into this article because I was reading a book on jquery and I didn't understand the utility functions so I googled and found your post.It was way better than the book How you presented about Jquery.
The article was really so awesome. It was so easy to understand. The way you presented the topic made a clear picture in my head about the whole jquery concept.Many Many thanks.

Anonymous Avatar Anonymous said...

Beautiful explanation. Make these type of details available for everything you know about web development. Thanks.

Anonymous Avatar Anonymous said...

I have been "learning" jQuery for the past few weeks from various articles on the web, but the more I "learned", the further I was lost.
I searched in Google search engine for "jQuery internals", "jQuery working mechanism", "jQuery architecture" and none of the results were to my expectation until . . . I came across this article in the search results.
Thanks a lot for providing a simple and clear understanding of the basics of jQuery.
This article took

Unknown said...

Thank you for taking the time to write your comment :)

sk said...

Hi Mike,

This is the first time i really got what jquery is....great article. Its simple and very well written. Thanks for the article.

Mani said...

thanks for sharing..
www.7eleventech.com

Mani said...

its use full information thanks
www.7eleventech.com

myths said...

Thanks a lot, It was really helpful and had fun reading it and definitely a boost for the basics. Just had a query (Sorry if it is only me) I was eager to follow your books on JQuery and JavaScript that you have mentioned in Next Steps but i cannot see the names of the books?

©2009-2011 Mike Gleason jr Couturier All Rights Reserved