Getting Started with jQuery

Jan 4 2010 by Louis Lazaris | 40 Comments

The web development scene is moving forward at a lightning-fast pace, and it’s imperative that developers continue to keep their skills fresh. If you’ve been involved in front-end design or development in any form over the past five years or so, then it’s very likely that you’ve experimented at some point with one of the popular JavaScript libraries, many of which have become quite prominent and are now used on a number of large commercial websites.

Getting Started with jQuery

In this article, I’ll be introducing and laying the groundwork for advanced JavaScript development with one of the most popular JavaScript libraries available: jQuery.

Although there are many beginning tutorials online that can provide a great starting point for jQuery development, in this article I’m hoping to go beyond just quick-start syntax and instead provide a solid overview of jQuery and discuss the benefits of using such a library. Of course, much of this information–outside of the syntax and other jQuery-specific details–will be applicable to any JavaScript library.

Why a JavaScript library?

To quote the official jQuery slogan: "Write less, do more." The role of a web developer is to create code that determines what will result from a user’s interaction with a web page. Web developers should not have to spend hours debugging browser quirks. Instead, they should be free to deal solely with the actions and the results. This is where a JavaScript library comes into play.

Overcoming browser differences

Different browsers handle DOM manipulation, transparency effects, and animation in different ways, requiring, in some cases, reams of code just to create a simple effect. Using a JavaScript library allows you to completely bypass all of those challenges, giving you access to an API (Application Programming Interface) that deals directly with the tasks you actually want to accomplish. All the challenges and issues common to JavaScript are dealt with behind the scenes, allowing you to integrate functionality without wondering whether or not it will work in a particular browser.

Unobtrusive JavaScript

Another impelling reason to use a JavaScript library is that all libraries allow you to include JavaScript in your pages unobtrusively, thus keeping your behavior layer (the JavaScript) separate from the content and presentation layers (the XHTML and CSS).

Accomplishing complex tasks with ease

Finally, a very powerful feature of any JavaScript library is its ability to manipulate any element or set of elements on a web page with just one line of code. Take, for example, the following HTML:

<div class="container">
  <ul class="list">
    <li>Text Here</li>
    <li>Text Here</li>
    <li>Text Here</li>
    <li>Text Here</li>
    <li>Text Here</li>
  </ul>
</div>  

Let’s say you wanted to use JavaScript to change the background color of the first list item element (<li>) in the unordered list above. Using pure JavaScript, your code would look something like this:

var myListCollection = document.getElementsByTagName("ul");
  for (var i = 0; i < myListCollection.length; i++) {
    if (myListCollection[i].className === "list") {
      myListCollection[i].childNodes[0].style.backgroundColor = "blue";
    }
  }  

Using jQuery, you can accomplish the same thing with just one, easy-to-maintain line of code:

$("ul.list li:first-child").css("background-color", "blue");  

Further reading

Understand CSS concepts

One area that is imperative to powerful jQuery development, is strong knowledge of CSS. The reason for this is because jQuery often utilizes CSS-based syntax to manipulate DOM elements. Here are some concepts that you should be quite familiar with before diving into extensive jQuery development:

  • Type selectors
  • Class selectors
  • ID selectors
  • Descendant Selectors
  • Child Selectors
  • Attribute Selectors
  • CSS Specificity
  • The Cascade & Inheritance

Most of the above CSS concepts should already be very familiar to any modern-day front-end developer, since any CSS layout would utilize these. jQuery not only incorporates the basic selectors (type, class, and ID), but it also uses descendant and child selectors, which aren’t supported by all currently-used browsers. But with jQuery, due to its built-in browser normalization, all selectors are supported equally.

Understanding that jQuery incorporates CSS syntax when accessing elements will greatly enhance your ability to quickly and easily create powerful JavaScript applications with jQuery.

Understand JavaScript concepts

In order to make full use of jQuery, it is a good idea to learn certain JavaScript concepts. Sure, you can do a ton of stuff in jQuery without knowing much about some of the concepts listed below, but you’ll have a bigger advantage in your jQuery development if you take the time to understand a few fundamentals, including:

  • Object creation
  • Properties of objects
  • Object literals
  • Functions as methods
  • Anonymous functions
  • Closures

Again, it is not necessary to fully understand any of the above concepts in order to start working with jQuery, but your abilities with jQuery’s API will increase greatly if you understand one or more of the above concepts.

The jQuery source code

Before getting started with any jQuery development, you’ll first have to download the latest version of the jQuery library and include it in your pages:

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>  

The above line of HTML should appear before any actual jQuery code, otherwise you’ll get errors.

Alternatively, instead of hosting the source code yourself, you could link directly to the most recent version on the Google Ajax Libraries API which can save you some server resources. (read more ways to offload website features).

jQuery syntax

Now that you have an overview of the benefits of jQuery, along with some understanding of concepts involved, let’s take a look at some syntax to get us started with this powerful library.

The jQuery wrapper

The jQuery wrapper is the function that is at the core of all jQuery commands. I used it earlier in one of the examples above. Here it is again:

$("li a");

The $ symbol is an alias for the jQuery function, so the above line of code could alternatively be written:

jQuery("li a");

But, for obvious reasons (e.g. to keep your code terse), you’ll rarely see that syntax.

The jQuery function shown in the above two examples returns an object containing an array of the DOM elements specified inside the parentheses (in this case, all anchor tags that are nested inside of <li> tags). Of course, in both examples above, we haven’t specified an action; all we’re doing is returning those DOM elements, which does nothing. In the next section, we’ll add methods that will act on the group of elements we’re targeting.

jQuery commands

jQuery’s API includes easy access to effects and other actions via built-in methods that would normally take dozens of lines of code to accomplish in a cross-browser fashion with pure JavaScript. For example, let’s add a "fade out" method to the code from the previous examples:

$("li a").fadeOut(); 

The above line of code "fades out" all anchor tags on the page that are nested inside of <li> tags. If we want to fade the anchors back in again, we just use the fadeIn() method:

$("li a").fadeIn(); 

Chaining commands

jQuery also allows developers to chain commands, stringing one after another. So, we could combine the previous two examples, as follows:

$("li a").fadeOut().fadeIn();  

The above code will fade out all anchor tags nested within list items, then immediately fade them back in. The number of chained items is infinite (or within reasonably set limits), allowing for numerous commands to work on the same group of elements, each happening in succession.

That’s just a small sampling of what’s possible with jQuery, and how easy it is to accomplish tasks that would normally take many lines of code, and a lot of browser testing. Although you’ll still do browser testing when running jQuery code, the results will virtually always be the same: cross-browser, unobtrusive JavaScript that’s easy to write and easy to maintain.

Running code when the DOM is ready

Earlier we touched on the concept of unobtrusive JavaScript, and how jQuery is written to allow your scripts to remain separate from content and presentation. So far, the code examples we’ve discussed would run fine as long as they were included at the bottom of an HTML page. If, on the other hand, they were included in the head of the document, they would fail to work because, at that point, the document tree has not yet rendered.

jQuery allows us to run our code only when the DOM is ready. This is done by means of the $(document).ready handler. The beauty of this handler is that it doesn’t make the code wait until the entire page finishes loading, as would be the case with a typical window.onload event. With the (document).ready handler, your code will run as soon as the DOM tree is finished rendering, before all images and other media have finished loading, thus minimizing load time.

Let’s try running our previous code example when the DOM is ready:

$(document).ready(function(){
  $("li a").fadeOut().fadeIn();
});  

The above code tells jQuery to run an anonymous function when the document tree is done rendering. The anonymous function contains the code we saw previously, which faded our anchors out, then immediately faded them back in again. This code could be included in the <head> of the document, near the bottom of the page, or anywhere else, and it would run exactly the same way.

The "ready" event is just one of the many events available through jQuery’s API. Others include click, dblclick, load, blur, keydown, submit, and more.

Further reading

Conclusion

jQuery is capable of so much more, and I’ve only just begun demonstrating its power and simplicity. But I think this suffices to provide a good overview, with some syntax basics, thus preparing beginning jQuery developers for easy-to-write and practical JavaScript code.

Further reading

Related Content

About the Author

Louis Lazaris is a freelance web developer based in Toronto, Canada. He blogs about front-end code on Impressive Webs and is a co-author of HTML5 and CSS3 for the Real World, published by SitePoint. You can follow Louis on Twitter or contact him through his website.

40 Comments

Chris

January 4th, 2010

Great article Louis. It’s always good to revisit the basics. What is your opinion on using Google Ajax libraries to host your jQuery file? I’ve heard pros and cons for it but I personally link to it on most sites that I use jQuery.

Jenna Molby

January 4th, 2010

Great post Louis!!

Alexa

January 4th, 2010

Great tutorial – gives good background and is easy to understand.

Lasse Chor

January 4th, 2010

Just what I needed..

Jimmy Day

January 4th, 2010

Thanks for the informative and extremely well-written article Louis. I’ve been developing websites for nearly a decade now and have been somewhat intimidated by all the various JS libraries out there, but this was an excellent jumping off point for getting started with jQuery.

David

January 4th, 2010

Pretty solid tutorial for people just learning. I’ll pass this along.

Louis

January 4th, 2010

@Chris,

Thanks, glad you enjoyed it. I haven’t looked too deeply into the pros and cons of remotely hosting your js libraries, but I have been leaning more towards that lately. It seems safe and practical enough, from what I’ve read.

Cory

January 4th, 2010

I must say that I was a little intimidated by jQuery when I first started looking at it. After using it for the past year though, I’ve been able to do things with jQuery that I wouldn’t dream of doing with plain ole javascript. Really exciting how the community has embraced it!

ajay

January 5th, 2010

Great Tutorials

Deepu Balan

January 5th, 2010

Bookmarked! Was actually looking for some beginner level JQuery tutorial. Thanks for this wonderful post… Will go through all the links provided once I manage to get some free time.

-Deepu

Gordon

January 5th, 2010

Great post, a handy one to bookmark and use as reference.

Thomas Nordén

January 5th, 2010

Great intro. I just started to learn about JQuery on lynda.com, but this is a useful addition to that. Thanks!

Michael Lajlev

January 5th, 2010

Writen in a nice an easy understandable language.

Matt

January 5th, 2010

This really is a useful addition to the already tutorials already available. Thanks Louis! It´s very easy to achieve amazing effects with Jquery but I often notice that I´m missing some of the JS foundations. This article will be helpful.

What I´m still looking for is a roundup tutorial on where to place JS code: when in the header, when in the footer, when inline, when in the head and when in a separate file. If someone can point me to an article explaining just that, that would be great.

Webjohn01

January 5th, 2010

Hello Louis!

It was a great article about JQuery. as we all know that it is one of the most popular javascript library that are used in modern websites.

Keep up the good work.

More thanks!

Prashant

January 5th, 2010

Thanks you for these tuts, my leacture makes this all sound so dull but you make it look much simpler. Keep up the good work!

Moreover i found good tricks of jquery here..

SMiGL

January 5th, 2010

good post assembly for beginners!

Jamie

January 5th, 2010

While I understand the need for articles to educate newcomers to various languages important to web development, this article barely explains anything of note.

Much like jQuery, its goal is not to educate but simply to demonstrate. I like jQuery, I think it is a great toolset, but the propogation of all the ‘plugins’ written against it are merely causing pages to be more and more bloated with inane garbage. Visiting your average jQuery site will usually show 5-6 JS files loaded into the header that take much more away from a site then they add.

Unless people bother to learn the core concepts behind JS, its prototypal nature, and how to properly use it, they’re just going to continue to copy+paste what someone else managed to stitch together. Garbage in, garbage out.

Shurandy Thode

January 5th, 2010

Good read especially for the beginner! Thanks for sharing.

Deepak Chaudhary

January 6th, 2010

HI Louis! Its indeed a great start to learn a great tool!! I have bookmarked this page! I was actually looking for some beginner level JQuery tutorial. Thanks for this wonderful post…

Regards
Deepak

Danilo

January 9th, 2010

Best tutorial for beginners, I hope there is a second one.

piczoom

January 10th, 2010

great post, good explanation method, bravo!

akkis

January 10th, 2010

Thank you! This tutorial really helped me!

Dave Kriegel

January 12th, 2010

I found using named-function very helpful when you just started using jQuery. check out this blog

Kelly Johnson

June 3rd, 2010

Good stuff here.

Bobby mac

June 26th, 2010

not to go off topic or “hijack” this post ,but what’s better/more powerful/more appropriate to pull users for media websites? It seems the user base behind jquery is ever growing while moo is, not. Following with the latest HTML5 and options under Modernizer.com’s
new attempt to support non-error coding or css3, is it more appropriate to integrate jquery? I’m using mootools and have a couple jquery scripts that work alongside my moo (magically) but get the feeling moo is going out with the old and jquery in with the new…

binam

November 10th, 2010

realy realy !! great article !
many many thanx!!!

amiya

March 4th, 2011

thanx a lot great article…..
solved a lot of questions

izel

March 24th, 2011

Excellent article and links for further information.
Thanks for posting them

Nash

April 22nd, 2011

Louis,

You have done a Fantastic job for JQuery begiiners like me by telling us about “What is JQuery”.

Thanks and job well done.

Amit

August 3rd, 2011

Excellent writeup. First thing to read if you are new to jQuery.

Nazmur

September 14th, 2011

Fantastic article! Thanks.

Rahman

September 14th, 2011

As a beginner in jquery I can say that, this article is very good for any newbies. Thanks a lot dude!

David

September 29th, 2011

Hi.

Just a note:

What seems to be missing from jquery starters is where to put the jquery code.

I tried putting a doc/ready snippet at the top of my linked js file and it didn’t work.

Would be good to see an example:

“In an external js file, put your jquery code ‘here’ “

Shaily

October 8th, 2011

This is an excellent article for jQuery basic understanding. Now I can think to design some good pages.

Shah Faisal

October 25th, 2011

very informative for the begginers

Jesse

November 9th, 2011

Great primer! Thanks!

john

April 3rd, 2013

good article. I was learning jquery for a while and this article still help me.

Satish koleti

June 25th, 2013

Louis Lazaris, Very good article. Simple and easily understandable.

Leave a Comment

Subscribe to the comments on this article.

Mobify empowers marketers and developers to create amazing mobile web experiences.

Mobify