jquery-jquery1JavaScript libraries are fantastic. I know many good web developers who have been reluctant to learn more JavaScript than they absolutely need to. I admit JavaScript can be confusing but it is a very powerful tool, especially with the power of AJAX. Below are a couple simple examples of very powerful techniques that can be achieved very quickly and cleanly using jQuery.

Example 1: Change the Style of a DIV element on Mouseover

Lists are a great tool for navigations but many times they don’t work or are too difficult to style. Lets say you wanted to make a vertical navigation out of DIV elements but you wanted them to change styles on rollover. Your HTML may look something like:

<div id="leftColumn">
        <div class="sidenavOff"><a href="#">NAVIGATION ITEM 1</a></div>
        <div class="sidenavOff"><a href="#">NAVIGATION ITEM 2</a></div>
        <div class="sidenavOff"><a href="#">NAVIGATION ITEM 3</a></div>
        <div class="sidenavOff"><a href="#">NAVIGATION ITEM 4</a></div>
</div>

Very simple and clean. Notice there is no inline JavaScript for the rollover effect. The beauty of jQuery is it can handle events for elements without nasty inline JavaScript. Here is the jQuery JavaScript to add rollover effects to this navigation:

    $("div.sidenavOff").mouseover(function(){
    	$(this).removeClass().addClass("sidenavOver");
    }).mouseout(function(){
    	$(this).removeClass().addClass("sidenavOff");		
    });

Easy aye? Analyzing the code you can see simple mouseover and mouse out functions where we’re removing the current class and adding the proper one for the time in the event. This will effect any DIV with the class of .sidenavOff on mouseover.

Example 2: Including HTML content in a Page using jQuery and Ajax

Suppose we had a div on our page with the ID of #lookup. When clicked #lookup1 we wanted the content from a file called search.htm to load in another DIV with the id #lookupContent.

With HTML you could link to a new HTML file that had this adjustment made. With standard JavaScript you could make a very lengthy AJAX request to load the page or with jQuery you can do it with ease. For example:

	$('#lookup').click(function() {
		$('#lookupContent').load('search.htm');
	});

This code will load the file search.htm and replace the contents of #lookupContent with whatever is in the search.htm file. Cake.

I will give a few more, simple jQuery examples in the near future. I am trying to convince as many developers as I can to take a look at the various JavaScript frameworks. There is a reason they’re such a hot topic these days.