JavaScript is pretty useful but it does demand a lot of coding. Luckily for all of us, there are libraries out there that make it extremely easy to use the power of JavaScript with a lot less code. I have been having a lot of fun with jQuery latetly and wanted to share a quick and easy tutorial on how to create a mouseover hover effect.

A similar effect can be easily accomplished using CSS and the :hover selector, but if you are new to jQuery, this tutorial is a good starting off point to familiarize yourself with how it works.

First you need to download jQuery. Grab the Production minified version off of their site. You will also need two images. I used the two below. I named them button.png and button-hover.png.

bavota-bwbavota

Now we can start to create the effect.

To make it all work, we first need to add the jQuery library script between the <head> tags.

<script type='text/javascript' src='http://yoursite.com/jquery.js'></script>

Now lets create the function that will make it all work.

<script  type='text/javascript'>
$(document).ready(function(){
	$(".button").hover(function() {
		$(this).attr("src","button-hover.png");
			}, function() {
		$(this).attr("src","button.png");
	});
});
</script>

Last but not least, we need to add our image to the page.

<img src="button.png" alt="My button" class="button" />

The one thing you need to make sure is that the classname in the jQuery function (.button) matches the classname of the image tag (button).

With everything in place you should have a file that looks like this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery Hover Effect</title>
<script type='text/javascript' src='http://yoursite.com/jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function(){
	$(".button").hover(function() {
		$(this).attr("src","button-hover.png");
			}, function() {
		$(this).attr("src","button.png");
	});
});
</script>
</head>

<body>
<img src="button.png" alt="My button" class="button" />
</body>
</html>

Try out the effect below.

bavota-bw

NOTE: If you are using jQuery with WordPress, you need to replace all the dollar signs ($) with the word jQuery due to other Javascript libraries that use the dollar sign.