jQuery 101 – Learning the Basics

By now most web designers and developers have a very good understanding of jQuery and its capabilities; for most it is their go to JavaScript library when adding some additional functionality or interactivity to their web pages.

However there are still plenty of people out there who are new to web development and who would like to get started with this great language but don’t know how to.

Well, this one’s for you!

What is jQuery?

In essence, jQuery is a powerful JavaScript library which makes life a lot easier for those of us with little (or no) JavaScript knowledge. It allows us to add JavaScript functionality to a web page using much simpler code. jQuery is particularly apt at adding event-handling, transversing, animations or Ajax interactions to a web page.

I don’t know about you, but that all sounds rather confusing and boring… But believe me it’s not! And once you get a basic understanding of jQuery, you’ll be WOW-ing yourself in no time. And the best way to get this basic understanding is just to get started.

Are you ready?

Installing the jQuery Library

To make use of jQuery you first need to make the script available to your webpage. There are a few options available when adding the jQuery library to your webpage but they basically breakdown into two options:

  • Downloading the latest source file and hosting it on your own website/server.
  • Linking to hosted files such as those on jQuery’s own site, on Google’s Libraries API or a few other hosted options.

Personally I almost always opt for linking to files hosted on an external source unless for some reason I am developing without an internet connection, and that pretty much doesn’t happen to me anymore! So I am going to show you how to implement the hosted option. So break open your favourite text editor and let’s get started.

Let’s create the basic HTML page structure first:

<!DOCTYPE html>
<html>
    <head>
        <title>jQuery 101 - Learning the Basics</title>
    </head>
    <body>
        <!-- My page content will go here -->
    </body>
</html>

We are going to link to Google’s latest (at time of writing) stable copy of jQuery. A quick search of “google jquery” should find the page you are looking for but for reference purposes it is:

https://developers.google.com/speed/libraries/devguide

Click on the jQuery (not jQuery UI) link in the table of contents. You are looking for the source path which references jquery.min.js. This is the compressed version of the file and will save you quite a bit of loading time – this is allows a good thing.

Now that we’ve got our reference, let’s add it to our page:

...
<head>
    <title>jQuery 101 - Learning the Basics</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
...

That’s it! How easy was that?

Your First jQuery Function

Now that the library is loaded onto our page, let’s prepare the page for our first jQuery function. Almost all jQuery code that you write will start with this function. It is the Document Ready function and basically it stops jQuery from running until the webpage has finished loading.

...
<head>
    <title>jQuery 101 - Learning the Basics</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
        // This is a JavaScript comment
        // Load the Document Ready function
        $(document).ready(function(){
          // The rest of our jQuery will go in here
        });
    </script>
</head>
...

Now that we have the boring bit done, let’s see what jQuery can do.

Your Second jQuery Function

Let’s create a paragraph with a link that hides the paragraph when clicked. Really very simple stuff with jQuery.

First let’s add the paragraph and link between the body tags:

...
<body>
    <p class="disappear">
        This paragraph will disappear when you click
        <a href="#" class="make-disappear">this link</a>.
    </p>
</body>
...

Now let’s add our jQuery:

...
$(document).ready(function(){
    $("a.make-disappear").click(function(){
        $("p.disappear").hide();
    });
});
...

Save your code as a HTML document (such as index.html) and load the page in your favourite web browser (such as Google Chrome or Internet Explorer). Now click the link to see your script run by hiding the paragraph.

Amazing!

Understanding the Syntax

Now that you have some code to look at, let’s try and understand what it’s doing by understanding the basic jQuery syntax. Every function in jQuery follows this basic structure, or syntax:

Basic Syntax: $(selector).action();

Let’s break it down:

  • The $ (dollar sign) defines jQuery. Other JavaScript libraries also make use of this sign so if you are mixing libraries you can use jQuery instead.
  • (selector) finds or queries elements in the HTML. So in our example the selector is (“a.make-disappear”) which tells jQuery to look for a hyperlink (a tag) with a class of make-disappear. The selector uses CSS syntax to query the DOM, such as .classname for classes and #idname for ids.
  • .action() is the jQuery action to be performed on the HTML elements. So in our example the action is .click(), in other words when the user performs a click on the link. We then run another function within the .click() action.

Our Syntax: $(selector).action(function(){$(selector).action();});

  • Within our .click() action we run another function by using function(){} and within this function we use $(selector).action(); again.
  • Our second selector is (“p.disappear”) which tells us that when a link with the class of make-disappear is clicked, look for any paragraphs (p tag) with a class of disappear.
  • Our second action is .hide(). What this tells jQuery to do is that when a hyperlink with a class of make-disappear is clicked, look of any paragraphs with a class of disappear and hide them.

Some Basic Events

Now that we have an understanding of our second jQuery function – making a paragraph disappear when we click a link – let’s look at some more basic events.

.toggle()

The .toggle() action combines the .hide() and .show() actions. Let’s create another link which toggles a span:

...
<body>
    ...
    <p class="toggle">
        <a href="#">Show/Hide</a>
        <span>This text will appear and disappear.</span>
    </p>
</body>
...

Now let’s add our jQuery:

...
$(document).ready(function(){
    ...
    $("p.toggle a").click(function(){
        $("p.toggle span").toggle();
    });
});
...

Save your file again and refresh your browser. By clicking the link you can show and hide the text wrapped in the span tag. Magic!

In the jQuery code above, instead of giving each element a class or id, I’ve only given the paragraph tag a class of toggle and then referenced other elements within the paragraph, just like you would with CSS. So by clicking the link within the paragraph with a class of toggle, we can show and hide the span within the paragraph.

All this is very nice, but we can do better than this! Introducing the .slideToggle() effect.

.slideToggle() and .find()

Now that you’ve gotten your head around some basics, lets speed things up a bit. In our next example we are going to look at .slideToggle() and .find(). As you probably have guessed .slideToggle() is very similar to .toggle() only with a slide animation effect. We are also introducing the .find() which helps us with the selector part of our query and could make our query up to twice as fast.

Let’s duplicate our previous code and instead of the paragraph having a class of toggle we’ll give it a class of slideToggle:

...
<body>
    ...
    <p class="slideToggle">
        <a href="#">Show/Hide</a>
        <span>This text will appear and disappear.</span>
    </p>
</body>
...

Now let’s add our jQuery:

...
$(document).ready(function(){
    ...
    $("p.slideToggle").find("a").click(function(){
        $("p.slideToggle").find("span").slideToggle();
    });
});
...

Save your file again and refresh your browser to see the .slideToggle() effect. Pretty sweet! But we can still do better than that!

Animation Speed

A lot of actions, including .slideToggle, allow us to dictate the speed of the animation. There are a few options available:

  • slow (600 milliseconds)
  • normal (400 milliseconds)
  • fast (200 milliseconds)
  • a custom speed in milliseconds

Let’s update our jQuery by adding the fast speed:

...
$(document).ready(function(){
    ...
    $("p.slideToggle").find("a").click(function(){
        $("p.slideToggle").find("span").slideToggle("fast");
    });
});
...

Once again, save your file and refresh your browser.

Notice that we put the word fast in quotes in our code above. The same goes for normal and slow. However if we want to dictate our speed in milliseconds we just enter the number, like so:

...
$(document).ready(function(){
    ...
    $("p.slideToggle").find("a").click(function(){
        $("p.slideToggle").find("span").slideToggle(1000);
    });
});
...

Our .slideToggle() effect will now take 1 second (1000 milliseconds) to complete.

.css(), this Selector and Basic Selector Filters

Let’s push the boat out again with our jQuery. In our next example we are going to look at one new action, the this selector and some basic selector filters. The action is .css() and as you can imagine, this allows us to add or edit CSS properties to our DOM elements. The this selector allows us to target the element which has been actioned, such as through .click(). The basic selector filters we will be looking at are :even, :odd and :last, and these allow us to target even numbered elements, odd numbers elements and the last element in our given query.

In our next example we are going to create a checklist. That is, an unordered list with zebra strips and a function which allows us to click on a list item and change its colour plus put a line-through the text, showing that this item has been completed.

On a side note, this example is for the purposes of showing how something could be done and not how it should be done – we’ll get to that later.

OK, first let’s create our simple list:

...
<body>
    ...
    <ul class="list1">
        <li>List item 1</li>
        <li>List item 2</li>
        <li>List item 3</li>
        <li>List item 4</li>
        <li>List item 5</li>
        <li>List item 6</li>
    </ul>
</body>
...

Now let’s style our list items using .css(). First let’s give each item some padding:

...
$(document).ready(function(){
    ...
    $("ul.list1").find("li").css("padding","5px");
});
...

Notice we are just running our usual selector with the .find() action and finally we are adding one CSS property to all the unordered lists-items – padding of 5 pixels on all sides.

Next let’s target all our even list items. Remember that arrays start with 0 so technically our first list item is even, not odd as you would expect. We’ll use the :even filter to do this:

...
$(document).ready(function(){
    ...
    $("ul.list1").find("li").css("padding","5px");

    $("ul.list1").find("li:even").css({
        "border-top":"1px solid #eee",
        "background":"#fcfcfc"
    });
});
...

Notice that this time our .css() action is a little different because we are specifying more than one CSS property. Make sure to remember this so that you don’t get tripped up in the future.

Now let’s style the other items in our list using the :odd selector filter:

...
$(document).ready(function(){
    ...
    $("ul.list1").find("li").css("padding","5px");

    $("ul.list1").find("li:even").css({
        "border-top":"1px solid #eee",
        "background":"#fcfcfc"
    });

    $("ul.list1").find("li:odd").css({ 
        "border-top":"1px solid #d3e9ff", 
        "background":"#e8f3ff" 
    }); });
...

And finally let’s add another border at the bottom of the last list item using :last:

...
$(document).ready(function(){
    ...
    $("ul.list1").find("li").css("padding","5px");

    $("ul.list1").find("li:even").css({
        "border-top":"1px solid #eee",
        "background":"#fcfcfc"
    });

    $("ul.list1").find("li:odd").css({
        "border-top":"1px solid #d3e9ff",
        "background":"#e8f3ff"
    });

    $("ul.list1").find("li:last").css("border-bottom","1px solid #d3e9ff"); 
});
...

If you save your document and refresh your browser you will see that we have created a very simple zebra strip effect.

Now let’s create our checklist functionality by using the this selector:

...
$(document).ready(function(){
    ...
    $("ul.list1").find("li").css("padding","5px");

    $("ul.list1").find("li:even").css({
        "border-top":"1px solid #eee",
        "background":"#fcfcfc"
    });

    $("ul.list1").find("li:odd").css({
        "border-top":"1px solid #d3e9ff",
        "background":"#e8f3ff"
    });

    $("ul.list1").find("li:last").css("border-bottom","1px solid #d3e9ff");

    $("ul.list1").find("li").click(function(){
        $(this).css({
            "border-top":"1px solid #fcf47e",
            "background":"#ffffea",
            "text-decoration":"line-through"
        });
    });

});
...

In this last query what we are asking jQuery to do is get any unordered lists with a class of list1 (ul.list1), find all the list items (li) within the unordered list, then, if any of the list items are clicked, apply the css following css styles only to the item that was clicked (this). Got it? Great, go check it out in your browser.

.hasClass(), .addClass(), .removeClass() and if Statements

Remember how I said that the last example showed how a checklist function could be done but it wasn’t how it should be done? Well let’s learn how it should be done and while we are at it we’ll learn about .hasClass(), .addClass(), .removeClass() and JavaScript if statements, plus also add the functionality to unselect items too. Exciting, eh?

OK, first duplicate the unordered list items from the previous example and give it a class of list2.

...
<body>
    ...
    <ul>
        <li>List item 1</li>
        <li>List item 2</li>
        <li>List item 3</li>
        <li>List item 4</li>
        <li>List item 5</li>
        <li>List item 6</li>
    </ul>
</body>
...

Easy so far. Next we are going to style our list using CSS rather than jQuery. So we need to create a stylesheet and link to it in our HTML head:

...
<head>
    <title>jQuery 101 - Learning the Basics</title>
    <link rel="stylesheet" type="text/css" href="styles.css" />
    ...
</head>
...

OK, next add the following styles to your stylesheet. These will look very familiar to you as they are the same styles that we used in the last example. The only difference to note is that I’ve swapped around the styles for odd list items and even list items. Notice that we are using CSS3 Pseudo-classes.

ul.list2 li { padding: 5px; cursor: pointer; }
ul.list2 li:nth-of-type(odd) { border-top: 1px solid #eee; background: #fcfcfc; }
ul.list2 li:nth-of-type(even) { border-top: 1px solid #d3e9ff; background: #e8f3ff; }
ul.list2 li:last-of-type { border-bottom:1px solid #d3e9ff; }
ul.list2 li.completed { border-top: 1px solid #fcf47e; background: #ffffea; text-decoration: line-through; }

We are almost done. Now just for our jQuery. We are going to run the same query as before. jQuery will find all the unordered lists with a class of list2, then will find all the list items within the unordered list. This time when the user clicks on a list item the jQuery will run an if statement. It will check if the list item has a class of completed by using .hasClass(), and if so will remove the class using .removeClass(). If it doesn’t has a class of completed it will add the class using .addClass().

...
$(document).ready(function(){
    ...
    $("ul.list2").find("li").click(function(){
        if($(this).hasClass("completed")) {
            $(this).removeClass("completed");
        } else {
            $(this).addClass("completed");
        }
    });

});
...

And that’s it. Go check it out in your browser.

Conclusion

Hopefully by the time you’ve completed this tutorial you’ll have some good basics about jQuery and how to use it. This tutorial only scratches the surface and you’ve only just begun to delve into the exciting world of jQuery.

So “Where do I go from here?” I hear you ask. I’d recommend continuing your journey on the W3Schools jQuery tutorial where you’ll cover what we’ve already learnt here, plus expand your knowledge even more by getting to grips with actions like .animate(), learning about callbacks, using Ajax and much more.

Not enough for you? Here’s some more useful resources:

Get The Source Code

You can download the complete tutorial source code by clicking on the big button below and unzipping the file.

Download Source File - jQuery 101 - Learning the Basics

This entry was posted in jQuery, Tutorials

Don't forget to share!
If you liked this post, please share it with your friends - Thanks!

Your Comments

  1. Upendra says:

    Great tutorial….
    I think in the last you make mistake…. may be intentionally……
    } else {
    $(this).removeClass(“completed”);
    }

    i think it will be

    } else {
    $(this).addClass(“completed”);
    }
    But i thank u for this…..

Leave a Reply to Upendra Cancel reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>