jQuery – Javascript Made Easy

jQuery – Javascript Made Easy

By Luke Dingle on June 21st, 2008 in Tutorials

jQuery is an extremely lightweight JavaScript framework that makes deploying client side web applications quick and easy. The base package has only what it needs and this tutorial gives you a good look at what jQuery can do for you.

Class Selecting & Changing

If you’ve managed to tear yourself away from the many effects on the jQuery site then it’s time to look at how jQuery can make many other things simpler. A common JavaScript task is to apply a certain effect to elements with a certain CSS class.

Normally this would require

Toggle Snippet

// This function will be applied to the onmouseover effect of all the elements with a class name 'testClass'
function foo() { alert('bar'); }

// get all elements
var ele = document.getElementsByTagName('*');

// count them
nm = ele.length;

// loop through and check className before applying the function to mouseover on the matching elements
for (i=0; i

The above has kept things simple but it still takes quite a few lines. jQuery can condense this down to 1 (not including the $(document).ready() part



    $('.testClass').mouseover(function () { alert('bar');});

Using the jQuery class selector ‘.testClass’, we can add the function in one single line. When would you need more than one line? Well, not very often. Let’s say you wanted to add a function and then hide all of the elements (with an animation) before changing the text colour of each element. I won’t bother with the normal code because it will get a bit big but let’s see how you might do it with jQuery

Toggle Snippet

    $('.testClass').mouseover(function () { alert('bar');}).hide('medium').css('color', '#FF0000')

Yep, you guessed it. This can all be done in a single line. The beauty of the jQuery object is that it always returns the element so you can string together an arbitrary number of operations on a set of elements.

Just for fun, I’ve given all the H3 elements in this tutorial a class of “showOff”. Make Them Lemon Yellow! Using jQuery

DOMinate

The Document Object Model is the W3 specification for interacting with structured documents ((x)HTML, XML). To do things the correct way as required by the DOM can sometimes be a little fiddly but jQuery has made DOM compliance as easy as it has made everything else.

We’ve already seen how easy it makes finding elements within a page with its selectors (of course the back end of this is traversing the DOM) so now let’s look at how you can actually modify the document using jQuery.

If, using normal JavaScript, I wanted to add a div to the body of the document on the fly and inside the div, I wanted to have a h1, two paragraphs and one strong tag it would require quite a chunk of action.

Toggle Snippet

// create the div
var newDiv = document.createElement('div');

// Create the h1
var h1 = document.createElement('h1');

// Add text to h1
h1.appendChild(document.createTextNode('This is H1 Text'));
// Add h1 to div
newDiv.appendChild(h1);

// create a paragraph
var newP = document.createElement('p');
// now a strong
var str = document.createElement('strong');
str.appendChild(document.createTextNode('This is strong'));
newP.appendChild(str);
newP.appendChild(document.createTextNode('This is some extra text for the paragraph'));
newDiv.appendChild(newP);
newP = document.createElement('p');
newP.appendChild(document.createTextNode('This is the text for the second paragraph'));
newDiv.appendChild(newP);

// add new div to the body
document.getElementsByTagName('body')[0].appendChild(newDiv);

So, there’s quite a bit going on here and as you can probably see, this can become tedious to do for large chunks of dynamic HTML. I could have used the innerHTML attribute found in most modern browsers but innerHTML is not a supported DOM property.

jQuery has the brilliant .html() and .append() (among other) functions that take a string of text, interpret it and convert it (almost 100%) into the required DOM functions for insertion into the document. Therefore, that big chunk from above could be converted to simply

Toggle Snippet


$('body').html('

This is H1 text

This is strong this is more text This is text for the second paragraph
');

Again, there goes jQuery reducing quite a complex script to a single line. You needn’t bother with the semantics in the background you can just relax in the knowledge that the document will be updated in accordance to the DOM recommendations.

As you saw in the script I wrote from scratch above, the DOM has many functions and jQuery includes quite a few easier to use versions of these. jQuery also has $(element0).after(element1) function that places a document element1 after document element0 — a function strangely missing from the DOM.

To see all of your options for manipulating the DOM with jQuery I again refer you to the documentation.

Clean Up With Ajax

The last part of this tutorial will show you the benefits of jQuery’s AJAX functions. All of the JavaScript libraries claim to simplify Ajax requests but in my opinion, none does it as elegantly as jQuery.

An Ajax request object can be a temperamental beast at times and to do it well, you need to take into account the many things that may go wrong during an AJAX request to the server.

Here is an example of an AJAX request written from scratch. (This is from http://w3schools.com/ajax/ajax_intro.asp — the general procedure for starting an AJAX event rarely changes so I am using this as an example)

Toggle Snippet

function ajaxFunction()
{
var xmlHttp;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
      document.myForm.time.value=xmlHttp.responseText;
      }
    }
  xmlHttp.open("GET","time.asp",true);
  xmlHttp.send(null);
  }

There’s quite a few lines of code in this and it includes very little exception handling. If the above goes wrong, you will have a hard time finding out why because it is only checking if the request has completed — not whether the response from the server was a good one. It is also only set up for a request using GET (sending data on the query string) and not POST which requires fiddling.

The same thing in jQuery can be achieved using:

Toggle Snippet


$.ajax({
  type: "GET",
  url: "time.asp",
  dataType: "text",
  success : function (text)
                {  alert(text); },
  failure : function (text) { alert('That was all wrong, wrong!!'); }
});

This is probably the longest bit of jQuery you will see but it does a whole lot more than the manual code above did. This simply says “GET the time.asp page and treat it as plain text when it arrives. If all goes well, alert me with the response but if it goes bottom up, tell me that too” This is taking into account the fact that AJAX request will sometimes break and with only an extra line, you will immediately know that the request broke.

You will notice in the above AJAX script the { something : ‘something else’} argument sent to the function. This is simply a ‘hash’ or object declaration. Many jQuery functions accept an options object as their argument and this is a shorthand way of declaring them at run time.

Having such an easy way of using AJAX opens up many possibilities, even sending more JavaScript from the server to run later.

Look at the jQuery AJAX documentation to see more.

jQuery Why Aren’t You Yet?

There is much more to jQuery than what I’ve been able to cover here and the beauty comes from finding out more and more about it. Once you learn to love this library, you will find it hard to go back and then you’ll discover the plug-in repository and jQuery UI and your JavaScript nightmares will be over.

I leave you with this last message.

Go!!

This Page’s Code

You will notice that the code for this page is using the jQuery object instead of $. This is because jQuery is running in compatibility mode to avoid conflicts.

Toggle Snippet

// Wait for the document to be ready
jQuery(document).ready(
function(){
// This is the code that toggles the boxA and boxB demos from above
    jQuery('#boxA').click(function(){jQuery('#boxB').toggle();});
    jQuery('#boxA1').click(function(){jQuery('#boxB1').toggle('slow');});
// This is the animation at the end of the tutorial, it goes many levels deep using the animate function
     jQuery('#jqg').click(function () {
        jQuery('#gb').hide('side');
        jQuery(document.documentElement).animate({scrollTop : '-=400'}, 1500);
        jQuery('#jqg').animate({bottom : '400px', left : '120px', opacity : 0.6}, 1500,
            function() {
                jQuery('#jqg').animate({width : '200px', height : '200px', opacity: 1}, 400,
                   function () { jQuery('#gb').html('It allows you to create effects and manipulate documents with very little effort. Usually no more than one line of code');  jQuery('#gb').show('medium',
                       function () {
                           setTimeout(function () {jQuery('#gb').animate({opacity : 'toggle'}, 300,
                               function(){ jQuery('#gb').html('You can create quite complex animations and change the content, style and structure of documents while still meeting the DOM recommendations'); jQuery('#gb').animate({opacity : 'toggle'}, 300);jQuery('#jqg').animate({borderBottomWidth : '12px', borderTopWidth : '12px'},  300,
                                   function () {jQuery(document.documentElement).animate({scrollTop : '+=400'}, 1800);jQuery('#jqg').animate({width : '350px', height : '150px', bottom : '60px', left : '70px', opacity : 0.8, borderBottomWidth : '1px', borderTopWidth : '1px', borderLeftWidth : '12px', borderBottomWidth : '12px'}, 2000,
                                       function () {
                                           setTimeout(function(){
                                           jQuery('#gb').animate({opacity : 'toggle'}, 300,
                                               function(){
                                                   jQuery('#gb').html('You can move things fast');
                                                   jQuery('#gb').animate({opacity : 'toggle'}, 300,
                                                       function () {
                                                           jQuery(document.documentElement).animate({scrollTop : '-=200'}, 300);
                                                           jQuery('#jqg').animate({left : '300px', bottom : '200px', borderLeftWidth : '5px', borderBottomWidth : '5px', borderRightWidth : '5px', borderTopWidth : '5px'}, 100,                                                           function() { setTimeout(function(){
                                                               jQuery('#gb').animate({opacity : 'toggle'}, 300,
                                                                   function(){
                                                                       jQuery('#gb').html('Or slow....');
                                                                       jQuery('#gb').animate({opacity : 'toggle'}, 300,
                                                                       function () {
                                                                          jQuery(document.documentElement).animate({scrollTop : '+=200'}, 1000);
                                                                          jQuery('#jqg').animate({left : '100px', bottom : '100px', width: '100px', height : '100px', opacity : 1, borderWidth : '1px'}, 3000,
                                                                          function () {
                                                                           setTimeout(function(){
                                                                               jQuery('#gb').animate({opacity : 'toggle'}, 300, function(){jQuery('#gb').html('Add elements...');jQuery('#toAppend').show();jQuery('#gb').animate({opacity : 'toggle'}, 300, function () {setTimeout(function(){
                                        jQuery('#gb').html('Flick!');jQuery('#jqg').css('backgroundColor', '#ffffff');
                                       jQuery('#jqg').animate({left:'-=2px'}, 100, function(){
                                       jQuery('#jqg').css('backgroundColor', '#FF0000');jQuery('#jqg').css('color', '#FFFFFF');
                                      jQuery('#jqg').animate({left : '+=4px'}, 100,
                                      function(){
                                         jQuery('#jqg').css('backgroundColor', '#cfedef'); jQuery('#jqg').css('color', '#000000');
                                         jQuery('#jqg').animate({left:'-=2px'}, 100,
                                         function() {
                                             jQuery('#gb').html('They're gone!');
                                             jQuery('#toAppend').hide();
                                             setTimeout(function(){
                                                 jQuery('#gb').html('You can contol the window...');
                                                 jQuery('#jqg').css('backgroundColor', '#cccccc');
                                                 jQuery(document.documentElement).animate({scrollTop : '-=650'}, 1800);
                                                 jQuery('#jqg').animate({left : '200px',  bottom : '700px'}, 1500,
                                                     function(){
                                                         jQuery('#gb').html('Colours...');
                                                         jQuery('#jqg').css('backgroundColor', '#FFBBAA');
                                                         jQuery('#jqg').animate({left : '23px', width : '150px'}, 1000,
                                                             function(){
                                                                 jQuery('#gb').html('And So Much...');
                                                                 jQuery('#jqg').css('backgroundColor', '#caeffe');
                                                                 jQuery(document.documentElement).animate({scrollTop : '+=650'}, 1800);
                                                                 jQuery('#jqg').animate({left : '10px', height : 'auto', bottom : '-20px', height : '20px', width : '400px'}, 2000,
                                                                    function(){
                                                                        jQuery('#gb').html('MORE!!');
                                                                        jQuery('#jqg').css('backgroundColor', '#cfedef');
                                                                        jQuery('#jqg').animate({width : '150px', opacity : 1, left: '0px', bottom : '0px', height : '20px'}, 1500, function () {jQuery('#gb').html('Play Again! jQuery R0xx0r5');});
                                                                 });
                                                             });
                                                     });
                                             }, 2000);}
);});
}
);}, 1000);
});
});
}, 5000);
}
);});
                       });
                                                           }, 5000);});
                                                   });
                                            });
                                            }, 5000);
}
);});});}, 5000);
});
                    });
             });
       });
// This function changes the h3 elements to yellow
jQuery('#h3Switch').click(function(event)
{
       event.preventDefault();
        if (jQuery('.showOff:first').css('color') != '#FFFF00')
        {
              oColour = jQuery('.showOff').css('color');
              jQuery('.showOff').css('color', '#FFFF00');
              jQuery(this).html('Eww, horrible! Change it back');
        } else {
              jQuery('.showOff').css('color', oColour);
              jQuery(this).html('Make it yellow again!');
        }
});
// This is the code that toggles the code snippet boxes
jQuery('pre a').click(function(event){ event.preventDefault();
                                                       jQuery(this.parentNode.getElementsByTagName('code')[0]).slideToggle('medium');});
});
});

var oColour = false; // Stores the original h3 colors

Pages: 1 2

Did you like it? Share it!
  • Delicious
  • DesignBump
  • DesignFloat
  • Digg
  • Facebook
  • StumbleUpon
  • Technorati
  • Twitter
About The Author
Luke Dingle

Luke Dingle is a professional web developer working in Tasmania, Australia. Although much of his time revolves around writing, then re-writing Python (Django), PHP and JavaScript code for others, he manages to find time to work on pet projects like http://www.openthource.com and http://www.lukedingle.com. Luke likes to juggle and play piano but usually runs out of time as his attempts to lobby the government for 3 extra hours in each day have so far failed. Tweet him @Rakuli

Comments
  • June 23rd, 2008 at 5:43 pm.

    Great post Luke!

    I also posted a short one on my blog a few days ago about looping through a table:
    http://jackfranklin.co.uk/single.php?contentid=83

  • June 27th, 2008 at 2:12 am.

    Great tutorial mate :D

  • June 28th, 2008 at 3:10 am.

    Thanks Jack and Monie. I’m glad it was helpful and look forward to seeing what you do with jQuery.

  • June 30th, 2008 at 10:15 pm.

    Nice post. I too have been leary about JS frameworks because I figure I can do it myself, but you make same valid points. Maybe I should set my pride aside and look into a framework.

  • July 3rd, 2008 at 1:06 am.

    Wow… jQuery is awesome.

    Thanks for writing this post Luke as I was reluctant to fully see the power of this amazing and lightweight package.

    I have been implementing all week since we spoke last and am finding it a real treat to finally see my application going AJAX.

    There are some teething issues though, I’ve yet to fully get AJAX form submitting happening. But as far as getting dynamic content up in a fancy manner with jQuery is a breeze.

  • July 3rd, 2008 at 9:03 am.

    Nice post. I too have been leary about JS frameworks because I figure I can do it myself, but you make same valid points. Maybe I should set my pride aside and look into a framework.

    Thanks Scott. You wouldn’t believe how hard it was for me to put the keyboard aside and let jQuery do some typing for me. It is a battle that I’m glad my ego lost though, it lets me concentrate on what I love — innovating interfaces.

    @Bobby

    Glad you’ve joined my on the jQuery bandwagon — the jquery.form.js plugin is an absolute godsend… I don’t think I’ll ever have to write another HttpRequest object again.

  • July 6th, 2008 at 11:03 am.

    Just like to add I think its a shame the jquery site seems to run terribly slow for me. As though its hosted on somebodies private modem. I don’t know.

    If you’re like me and having constant issues accessing their regular site http://docs.jquery.com/ load your browser to http://visualjquery.com/ which is an alternative to the documentation.

    I find it bizarre, that for such an awesome framework that is used so much that it appears to be quite limited in its documentation and that its own site doesn’t have the feeling of being streamlined. Some of these really popular plugins have 0-5 ratings so it seems like its not a hub of activity when it is. Anyways. It rocks.

  • Japh
    October 7th, 2008 at 9:38 am.

    In case you haven’t checked out the jQuery site in a while (which I doubt!), they’ve had a face lift, and seem to be quicker to access. I guess if it’s slow, that’s really probably just a testament to the fact they must have a heavy traffic load thanks to all of us!!

    Also, you might want to check out http://ui.jquery.com/ if you haven’t already, to see some of the fancier demos of what you can do with javascript, and simply with jQuery ;)

    (I’m a convert!)

  • March 9th, 2009 at 11:21 pm.

    Yes making your own framework is a labor of love. Just remember its a better idea to get a divorce rather than kill your cheating spouse.

    My framework, VVED, Very Versatile Electronic Document is the culmination of about 6 years work. Its basically the core of a pure javascript game engine, but you can use it to make pages too. :)

Trackbacks

Toggle Trackbacks

  1. [... What is jQuery? * If you prefer to see things work, head to the bottom of page 2 in this tutorial to see a demonstration of jQuery's effects. If you have yet ...]

  2. [... What is jQuery? * If you prefer to see things work, head to the bottom of page 2 in this tutorial to see a demonstration of jQuery's effects. If you have yet ...]

  3. [... What is jQuery? * If you prefer to see things work, head to the bottom of page 2 in this tutorial to see a demonstration of jQuery's effects. If you have yet ...]

So, what do you think?

x