Friday, November 6, 2009

Write Faster and Easier Javascript With jQuery

jQuery is "a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML." In plain English, it is a library that you include on your web page that allows you to add Javascript code much easier than writing out old-fashioned code.

The $ function

Taken from Wikipedia, "one of the critical concepts in any jQuery code is the so called '$' function. '$' is actually an 'alias' for the 'jQuery' namespace."

Example: Toggle a Div Visibility

To toggle the visibility of a div with a simple click of a button, add this code to the <a> tag:
<a onclick="$('#divid').toggle();">

Replace 'divid' with the ID of your div. Simple as that. Voila -- you have a DIV that hides and shows with the click of a button (or a link, in this case).

Not Impressed Yet?

It works great, but it's not quite smooth enough. Let's slow down the transition a little. That sounds complicated, right? Well, with jQuery it's as easy as adding one word to the code. Simply add the word "slow" to the toggle script like this:
<a onclick="$('#divid').toggle('slow');">

That's it! And when you get bored with toggling your divs, explore the many plugins on the jQuery site:
http://plugins.jquery.com/

Doesn't Work For You?

Don't forget to download and include the jQuery file:
<script type="text/javascript" src="jquery.js"></script>

0 comments:

Post a Comment