Monday, April 6, 2009

jQuery = Javascript - fuss + fun


Beginnings


Before we get to jQuery, we need to take a look at it's foundation: plane-jane javascript. Why? Sweet & Sour baby, we gotta taste it.

To understand our love/hate relationship with javascript, we need to go back to it's birth. In December 1995, a little browser named Netscape shipped with the hot new
javascript scripting language built in. Developers sang of the power of Dynamic HTML by means of this new tool. All was well in the world, birds sang, people danced & made love. Not to be outdone Microsoft quickly got to work creating their own version... and about a year and a half later, riding on the back of Internet Explorer 3, JScript emerged.

Now don't get me wrong... javascript on IE sounds like a Good Thing right? The same great tool working on two browsers now! Only one problem:


Javascript != JScript


So a few nuts and bolts were in the wrong spots. The mixture of Javascript and JScript lead to the new world of cross-browser scripting bugs, which showed it's ugly face in when doing DOM manipulation or AJAX (aka XMLHTTPRequest).
Scripts that worked great in Netscape broke in IE and vice-versa. Coders eventually singled out these bugs and shared them with each other, and being proficient in the awkward cross-browser differences was a need-to-know for web developers.

To see some examples, check out this javascript DOM reference. Note the text in red.

Enter jQuery

Well what do you do when you have a problem like that? jQuery's answer seems to be right: Abstract it! jQuery knows all the subtle javascript differences and by using it's interface directly you can hand the problem down. Not only that, jQuery knows that javascript lives and breaths DOM manipulation, so it provides a handy set of CSS or XPATH selectors for you to work with. Need to find a <li> with a class attribute of "redguy" that's nested somewhere in a <ul> with an id of "mylist" and change it's class to "blueguy"? Sounds a bit complicated, but with jQuery it's as easy as apple pie:


// change with jquery
function change_jquery()
{
$('#mylist li.redguy').removeClass('redguy').addClass('blueguy');
}


Here we are using CSS selectors to first select the list with id "mylist", then dig in and find the li's with class "redguy" inside of that. jQuery works with collections (or arrays) of objects, so the above code would return a set of DOM objects and manipulate them all at once. In addition, jQuery supports 'method chaining' by adopting the convention of each method returning the collection of jQuery objects it has touched. This let's us add and remove the classes we want in a single line. Let's compare that quick snippet to native javascript:


// change with javascript
function change_js()
{
ul = document.getElementById('mylist');
lis = ul.getElementsByTagName('li');

for( i in lis )
{
if(lis[i].className == "redguy")
lis[i].className = "blueguy";
}
}


Much more verbose, and slightly harder to read. jQuery is the clear winner here.

See the working example.

AJAX Anyone?

Not only does jQuery kick butt in DOM manipulation, it's got a nice arsenal for AJAX requests as well. AJAX is used to send information behind-the-scenes to the webserver and asynchronously retrieve the response, which is sometimes (but not always) in XML. Hence AJAX = Asynchronous Javascript And XML.

"Would you like a page refresh with that?"
"No thanks."

So why do we want to do this? What's wrong with just submitting the page and waiting for the whole thing to refresh? Well, often times only a small bit of the page itself will change when you are interacting with it.

For instance, you fill out an application online and submit it, wait for the page to refresh, only to be presented with the same page plus a little red sentence next to one of the fields: "Please enter a valid email." Seems like an awful waste of time and bandwidth for such a small update. Let's check out a solution using jQuery & a serverside validator using PHP:

jQuery:

// validate
function validate()
{
// pull email and phone values
var email = $('.email').val()
var phone = $('.phone').val()

$.post('validate.php', {email:email, phone:phone}, function(dat)
{
res = eval('(' + dat + ')');

// find errors
var errs = "";

if( !res.email ) {
errs += "invalid email\n"
$('.email').css('border', '1px solid red');
}
else
$('.email').css('border', '1px solid green');

if( !res.phone ) {
errs += "invalid phone number\n"
$('.phone').css('border', '1px solid red');
}
else
$('.phone').css('border', '1px solid green');

if( errs == "" ) // no errors?
alert('All data is valid!');
else
alert(errs);
})
}


and the corresponding PHP:

// validate and send result
$res = array(
'email' => valid_email($_POST['email']),
'phone' => valid_phone($_POST['phone'])
);

echo json_encode($res);

// validation functions
function valid_email($email) {
return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email) !== false;
}

function valid_phone($number) {
return ereg("^[0-9]{3}-[0-9]{3}-[0-9]{4}$", $number) !== false;
}


Here we're using jQuery's $.post() function, which takes in 3 arguments: the URL to post to, the data being posted (in a javascript dictionary), and the function to call when the result is received, which we are inserting directly using an anonymous function. This function is passed the output of the serverside script, which we're calling 'dat'.

Instead of using XML, we're using JSON here because it's more lightweight and requires less code for us to encode/decode. JSON stands for 'javascript object notation', and it's a handy way to pass data around when using AJAX. Because the result is native javascript, all we have to do is eval() it to decode the data structures into their javascript counterparts. In PHP, we are using the json_encode() function to encode our native PHP data structures to a JSON string. An example of the raw output from the PHP script might be:


{"email":true,"phone":false}



JSON libraries are available for all major development languages, and you can find one for your preferred language at the bottom of this page.

See the working example here.


Animations and Effects and and UIs... OH MY!

jQuery knows what you want.. and what you want is a beautiful user interface. Shiny things, slidy things, things that change colors... it's all available at the tips of your fingers with the animation suite jQuery provides.

Say we want to animate in a <div> with some info when the user presses a button. The div has an id of "hiddenguy". Here's the code we'll need:


$('#hiddenguy').show('slow');


That's it! Short, simple, to the point. In our working example, we add a timer to hide the box after 2 seconds:

See the working example here.


More more more!

Want to know more? The full jQuery API can be found here.
Read it, use it, love it!

jQuery is the gift that keeps on giving. In addition to all of the above, it also has a plugin system, so everyone can build and share their jQuery creations. To see a list of everyone's plugins, check out the jquery plugin page.

I hope this has been a nice introduction to jQuery and it's various uses. So remember, if you ever need to go Web 2.0, jQuery is where it's at!