jQuery – Javascript Made Easy

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 to hear about jQuery, it is quite possible that your house rivals Australia’s Uluru as the largest single standing rock in the world. Now that you are excited to hear the rock you are living under has broken a record, head over to http://www.jquery.com and download the latest release so you can play with the code as you read through this introduction to jQuery.

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, its huge plug-in repository and spin-off site (jQuery User Interfaces) has everything you would ever want.

Why Choose jQuery?

It’s a hard thing for me to admit, I have spent a lot of time learning, writing and tweaking JavaScript over the years. I have progressed through the dirty href=”javascript:someFunction()” links, I have passed the in-page event handlers and arrived out the other side into the peaceful and clean world of the the Document Object Model (DOM). Throughout this time, I have put many hours into many lines of code and I was balking at the suggestion of using a JavaScript library.

“It’s okay, I can write it myself!” was a common exclamation, “Why would I use a library? It’s unnecessary overhead for my site” was a common question. Valid concerns? Perhaps. More like 5% logical reasoning and 95% pride. I had fallen into the trap of many a web developer; I had the skills and ability to write the code and brought the world down onto my shoulders by attempting to make a ‘newer’, ‘better’ wheel every time I built a web application. A few months ago, I took a leap, I had an epiphany and accepted that the wheel had been working pretty well for quite some. I decided to delegate the everyday JavaScript tasks that took up so much of time (simple transitions, per class JavaScript on elements, inserting/removing elements from a document) to a JavaScript library.

jQuery was not my immediate choice, there are many feature rich, well-supported JavaScript Libraries available. The major contenders (other than jQuery) that I encountered in my initial research were:

All three of these libraries are fantastically useful libraries, all have been written and are supported by experts in JavaScript (gurus even) and all of them allow you to quickly implement client side applications without the grinding and browser specific tweaking required by an app built from scratch.

My decision to use jQuery in favour of the other available libraries was based on a few requirements I had for whichever I chose:

  • It had to be lightweight (jQuery is only 16Kb when served compressed not to mention the script hosted with Amazon that allows any website to link to jQuery straight off Amazon.com meaning many users will already have the script stored locally in their cache http://code.jquery.com/jquery-latest.js.)
  • It had to use the DOM almost exclusively (jQuery does this and can traverse XML documents out of the box)
  • It wouldn’t conflict with the namespace of too many of my own scripts (jQuery bases everything around a single object set to the variable $ and even the variable name can be changed if there is conflict. For example, prototype uses the same global variable)
  • I didn’t want using the framework to feel like learning a new language entirely (as you’ll see, the only way jQuery would feel like using another language would be if you did not speak English)

If your expectations or requirements for a JavaScript framework differ from mine, I still recommend you give jQuery a chance but, having said that, do not discount the other frameworks as they all have much strength that you could benefit from. Remember, the wheel works fine.

The JavaScript to Prove It

Now that we are on the same level, (jQuery pwns writing everyday JavaScript from scratch), I’ll take you through some examples of the tasks that you might use jQuery for and the equivalent code you would have to write in order to do it without this helpful little library.

The Display/Visibility Toggle/Transition

It’s about as run-of-the mill as you can get in the world of JavaScript; doing something causes a page element to appear and disappear.

To write this from scratch isn’t a huge feat in itself. Let’s say that clicking on box a, will reverse the display state of box b.

Toggle Snippet

// First get the reference to box a so we can add the onclick handler to it
var boxA = document.getElementById('boxA');

// Now add a function to the onclick handler that gets boxB and changes the
// style.display attribute to 'block' or 'none' depending on its current state
boxA.onclick = function () {
       var boxB = document.getElementById('boxB');
       // is it hidden?
       if (boxB.style.display == 'none')
               boxB.style.display = 'block';
      // no? hide it then
      else
               boxB.style.display = 'none';
}

Not too involved right? The other problem we might have to contend with here is the fact that these elements might not have loaded yet and as such, we would have to add the .onload event handler to the window object so there isn’t an error when the page loads.

jQuery has a fantastic way of overcoming the problem mentioned above and it comes in the form of the $(document).ready() function. By placing your code inside this function, you can guarantee that your page will be fully loaded and ready to handle requests before any JavaScript is applied to it.

Let’s have a look at the jQuery method of toggling en elements display.

Toggle Snippet


// put code inside the $(document).ready() function
$(document).ready(function()
{
         // set up document so that clicking boxA will toggle boxB
         $('#boxA').click(function(){ $('#boxB').toggle();});
});

That’s it, three lines (if you remove the comments). jQuery has a very intuitive way of selecting elements. To select an element by id use # followed by the element’s id. You can also pass a reference to an object, a class name (. followed by the class name) multiple id’s at once (separated in the string by commas), just a tag name (no # or . required).

The full list of selection methods can be found in the jQuery Documentation.

So that is a very small thing to have to do and if you’re like me you’ve done it so many times with JavaScript that it hardly warrants a JavaScript framework. What if I change the jQuery code above to:

Toggle Snippet


// put code inside the $(document).ready() function
$(document).ready(function()
{
         // set up document so that clicking boxA will toggle boxB
         $('#boxA').click(function(){ $('#boxB').toggle('medium');});
});

Only one difference, one argument passed to the toggle() function. The difference is outlined below:

Before

Box A (Click Me)
Box B (watch what happens)

After

Box A (Click Me)
Box B (watch what happens)

You can see the difference here. What started out as a simple hide/show of an element has now become a graceful transition (including opacity, width and height). This is where the power of jQuery starts to emerge, it makes simple things simpler while at the same time making it appear more impressive.

Now consider what code would need to be used to achieve this same effect using JavaScript written from scratch. This tutorial would become quite bloated if I were to write it all here but the process would be.

  • Create a class that can be used to make objects to modify
  • Add class properties that will keep track of an objects current height, width, opacity as well as the destination height width and opacity.
  • Write methods that will change the style of the object in increments that also has tapering logic to slow the effect as it approaches its finish.
  • Keep track of intervals/timeouts and clear when the animation is over
  • Test and tweak for numerous browser issues that arise

Needless to say, there is quite a bit more work involved than what jQuery requires. jQuery has a host of additional effects that you can use including the ability to animate any css property that you wish.

See all the jQuery default (not including plugins or jquery UI functions) effects.

Pages: 1 2

10 Comments on "jQuery – Javascript Made Easy"

  1. 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

  2. Monie says:

    Great tutorial mate :D

  3. Luke Dingle says:

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

  4. 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.

  5. Bobby says:

    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.

  6. Luke Dingle says:

    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.

  7. Bobby says:

    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.

  8. Japh says:

    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!)

  9. 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. :)

  10. Roman says:

    For someone that cares about whether a photo was real or Photoshopped, maybe you can try Photoshopped Image Killer. This free website maybe can give your answer. By analyzing something like Exif data or so. But it it really bad that the seller is touching op those images? Maybe he just sharpened the image and removed some things from the background.

Got something to say? Go for it!