Wednesday, October 31, 2007

Advantages of the jQuery Ready event

I've been working with jQuery for a few weeks now as part of a project, and I love it. I've always preferred to roll my own JavaScript, but from now on I plan to write all of my JavaScript utilizing the features provided by jQuery.

One of the most significant features of jQuery is it's document ready function:

$(document).ready(function(){
   // Your code here
 }); 

It allows you to assign functions that will execute when an event like a mouse click occurs on the selected HTML element(s) (hyperlinks, divs, buttons, etc.). This allows you to separate the JavaScript calls from the HTML code itself--instead of writing:

<input id="mainLink" onclick="showPic();" type="button" value="Show Picture" />

...you can assign the click event to the mainLink button in a separate JavaScript file (referenced by the HTML file)...

$(document).ready(function(){
   $("#mainLink").click (function () {
     showPic();
   });
 });

...and leave the button free of that markup:

<input id="mainLink" type="button" value="Show Picture" />

The other benefit to this technique is that if you have a client that likes to alter the HTML code of the pages you wrote for them, but you're afraid they might screw up the JavaScript calls in the page, you can use jQuery to create all of the event handlers and the client won't have to worry about avoiding JavaScript code in the document.

No comments:

Post a Comment