Foreword

The following is a quick crash course in using jQuery.  If you’ve never used jQuery before and want to know to how without reading a ton, this is the tutorial for you.

Getting Started

First download the latest version and include it in a page.  Grab the minified version for speed or if you want to read through the code yourself, grab the uncompressed version.

http://docs.jquery.com/Downloading_jQuery#Download_jQuery

Next simply include the library in your HTML page just like any other JavaScript file.

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

Now we’re ready to start using it.

Dom Traversal

So how do we select a node or nodes.  We have a few different choices, we can use CSS selector syntax, or we can use xpath syntax.  Let’s try an example on the following markup.

<html>
    <body>
        <div class="container">
            <span  id="title">Hello World</span>
        </div>
    </body>
</html>

To apply a standard CSS selector we could use something like “.container #title{ style }” or just “#title{ style }”.  Same with jQuery, here’s an example:

<script type="text/javascript">

$(function(){
    var titleSpan = $(".container #title");
    //title span is now set to the span title node
    titleSpan = $("#title");
    //this does the same as well. 
}); 

</script>

Now if you’re unfamiliar with jQuery, the above syntax may look a bit odd but here’s the breakdown.  “$” is an alias of the jQuery object, which is what you’ll use to interact with all jQuery APIs.  The long hand for of the above would look like this:

<script type="text/javascript">

$(document).ready(function(){
    ...
});

</script>

Both do the same thing, wait until the document has fully loaded, then process the function passed into the ready event.  There are several methods for traversing the DOM.  To view the entire list checkout:

http://api.jquery.com/category/traversing/

DOM Manipulation

So how do we work with the DOM, change it’s contents, etc.  jQuery makes this really easy, and here’s how.  Let’s say we wanted to get the text content of the title node using the following HTML.

<html>
    <body>
        <div class="container">
            <span id="title">Hello World</span>
        </div>
    </body>
</html>

Here’s all we need to do.

var titleText = $("#title").text();

Boom! Done!  Very easy.  But what about changing the text contents of the node. Again:

$("#title").text("Hello Dolly");

Pie!  So if you pass an argument to the text method, it sets the content, without an argument, it retrieves it.  What if we needed to get the innerHTML value of a node.  Here’s what we do:

var html = $(".container").html();

That’s all there is to it, this example grabs the container class and retrieves the html content of the node.  What about setting it you ask? Check it out:

$(".container").html('<span id="footer">Goodbye</span>');

That’s all there is to it.  For more information on DOM manipulation, have a look at:

http://api.jquery.com/category/manipulation/

Working With Events

So now it’s time to be productive.  Let’s do something semi-based in the real world.  Let’s say we have a list of anchors that we want to attach a click event to.  Now the old school approach would be to do something like this:

var els = document.getElementsByTagName("a");
int len = els.length
for(var i=0; i<len; i++){
    if(els[i].className == ".showImage"){
        els[i].onclick = function(event){</pre>
<pre>            ...
        }
    }
}

This approach would allow us to get all the anchor elements off the page, then iterate each to find a match for class showImage, then bind a click event to that node and continue.  Using jQuery the same thing can be done if far less code:

$("a.showImage").click(function(){
    ...
});

Quite a difference, but both perform the same functionality.  In jQuery a selector can return a single or an array of elements depending on the markup and selector syntax used.  If the above looks a little confusing, consider this example:

$("a.showImage").each(function(){
    //this will return all a.showImage and call this each function on a per returned node basis
    //basically, this is a for each

    var anchor = $(this); //returns the current iteration object of each

    anchor.click(function(){
        ...
    });
});

The above does the same as the example before it.  Difference is the amount of code written and for demonstration purposes you can hopefully better understand what’s going on behind the scenes.

So now we now to to bind events, but what about unbinding events.  This example should help:

$("a.showImage").each(function(){
    var anchor = $(this);
    //bind the click event to the anchor
    anchor.bind("click", function(){
        ...
    });
    //unbind the click event from the anchor
    anchor.unbind("click");
});

When you use object.click, it’s the same as calling the bind() method of the object.  Therefore to remove the bind(), simply unbind().  For more information on handling jQuery events see:

http://api.jquery.com/category/events/

Side note: Current jQuery notation prefers the use of on() and off() in place of bind() and unbind(). The approach is easier to remember, use and has much better live DOM effects.

Conclusion

That’s about the gist of it.  The rest you should be able to discover on your own.  If you have any questions or find anything I’ve mentioned here to be confusing, please feel free to ask in the comments.


2 Comments

dink · August 17, 2012 at 11:37 am

2nd sample code in DOM Traversal section is missing ); at the end of function definition

GodLikeMouse · August 27, 2012 at 4:33 pm

Thanks, sorry about that. It has been updated.

Leave a Reply

Avatar placeholder

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