Saturday, May 12, 2007

Sliced Bread

I just happened to be taking a look at Thickbox again the other day (which functionality-wise is an extension of Lightbox), and I noticed that it was using the jQuery library. Since I'd never heard of this library before, I decided to investigate. It turns out this is the single sweetest javascript library I've come across (in other words, the coolest thing since sliced bread :P), and will most likely change the way I develop with javascript in the future.

Normally, if you have a div element on your page with an ID of "foo", you'd grab it like:

document.getElementById("foo")

With jQuery you'd grab it like:
$("#foo")

or
$("div#foo")

Similarly, if you have a class named "foo_class" then you would query that like:
$(".foo_class")

You could even query every div in the page like:
$("div")

Another huge benefit is $(document).ready(). Normally you would code off of the window.onload() event, but if you have a lot of images then your script might not fire off for a little while. $(document).ready() doesn't wait around for all the images to load. As soon as the DOM is ready, your script starts firing off.

As an example, here's how you might stop all the links on your page from working:
$(document).ready(function() {
$("a").click(function() {
return false;
)};
)};

jQuery also returns itself which makes it chainable. This means that instead of writing the following with 3 lines (one to add a class, one to show it, and one to set the innerHTML), we can just use this one line (for example):
$("a").addClass("test").show().html("foo");

jQuery also has other cool things like an iterator so you can write foreach loops, simple effects, and even special functions to make ajax/json easier. There's also a good community of users who have made plugins. Some of these plugins include:
  • Interface (an effects library similar to script.aculo.us)
  • Thickbox
  • TableSorter (makes it easy to dynamically sort a table)

Documentation can be found here, here, here, or here

3 comments:

Brainiac said...

Mootools is best. Less kb of Javascript. More extensions, etc,...

.. Dallas Meow >^^< said...

I may never close this page -
I need to learn soooo much!

Vurdlak said...

mr.

your blog did me great favor in learming random post trick. you are true hacker, I only beleive you lack a little in design (no offence,) and beleive if you made your blog little lighter in color (white, etc.) it would be much easier to read (bigger audience). also you can make comments box to add coments pop out /like I did in my blog moillusions.com

many thanks again, and I reccomand you remove black/purple tempalte since it's hard to follow...