0

jQuery Basics

Posted February 22nd, 2009 in Uncategorized by Alex Barberis

So here is a quick post on some jQuery basics. I’ve found this script library extremely useful lately. It’s saved me tons of time and I wished I had adopted it sooner. “Write less, do more” is for real. I’m a believer!

The first thing jQuery offers is the document ready function. This is great because your code will not execute until the DOM is truly ready. Here you can manipulate any elements or execute code. This is much more efficient than using the standard onload event.

$(document).ready(function() {
   // do stuff when DOM is ready
});

Now you need to interact with an element. This is quite easy. Let’s say we had a link we need to manipulate.

<a id="link">Click Me!</a>

Any time that you need to reference an element you simply use $(“#id”). So here are some quick things that we can do.

Change the onclick function:

$("#link").click(function(){
   alert("You clicked on the link!");
});

Append content to the link:

$("#link").append("New text inside the link");

Note: When you are checking for the existence or an element do NOT do the following:

if($("#link")) { //object exist };

This is wrong as each time you use the $(“#id”) convention you are asking for a jQuery object so you will get one even if the element is not there.

To correctly check for the existence of an element use the following code:

if ($("#link").length > 0 ) { //now we found it } 

You can see how easy it is to start manipulating things with this easy to use syntax. This is just the beginning . This is a very powerful framework that also has tons of third party plugins for many specific needs.

For more information on jQuery visit the following links. There is plenty of stuff on there to get anyone started.

jQuery Documentation

jQuery Plugin Repository

More to come when I have time!

Leave a Reply