Monday, 16 February 2009

jQuery: First Impressions

Working on some UI stuff today I started investigating and using jQuery (http://jquery.com). My first impressions are positive as it makes a lot of the more cumbersom bits of Javascript much easier. Here are some examples of some of the stuff I've used so far:


Selectors


Gone are the days of document.getElementById or using a for loop to iterate through an array returned by document.getElementByTagName. jQuery makes it much easier to selected items from the Javascript DOM using the new $ function:

  • To select an element by ID, use: $('#someId')

  • To select all h1 tags: $('h1')

  • To select all h1 inside the someId element: $('#someId h1')


Effects


There are lots of effects with jQuery. So far I've only used the show and hide effects. The longer winded Javascript:
myElement.style.display='none'

or
myElement.style.display='block'

has been replaced by the shorter and more intuitive:
myElement.hide()

or
myElement.show()

Also, if you fancy a bit of fading effect, you can simply add a number of milliseconds fade time in the method call:
myElement.show(250)

will show myElement in a 1/4 of a second fade in.

Utility Functions


jQuery enables you to replace the old-style, cumbersome for loops commonly used to iterate through an array with the easy to use each function. Check out the following example:

var names = ["Aaron", "Glenn", "Ian"];
names.each(function() { alert(this); });

This simple code will iterate through the each name in the array and use it in a Javascript alert.

Cookies


As well as jQuery, I've also discovered a cookie library that is built on jQuery that makes using cookies in Javascript a breeze. The library is courtesy of Klaus Hartl and can be found at http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/. As with all open source, the use of this library is done at your own risk!


The cookie library allows access to browser cookies using the following syntax:


  • Get a cookie value: $.cookie('cookieName')

  • Set a cookie value: $.cookie('cookieName', 'value')

  • Delete a cookie: $.cookie('cookieName', null)

  • Set a cookie value with a particular expiration: $.cookie('cookieName', 'value', { expires: 5 }) // expires 5 days in the future



That's it for now... I can say I'll be investigating jQuery further and am excited about what other goodies I'll find!

No comments:

Post a Comment