Simple JQuery Image Rollover With Preload
A Web Development article written by Ryan Burnette on July 29, 2010.I used to do all my image rollovers with background positioning. I liked this method because it could be done completely with html/css. By putting the :hover only on anchors I could cover that piece of junk IE6 without fooling with Javascript. JQuery has become my best friend though.
There is a great, simple way to use JQuery to add a class on hover… like so.
$(‘ul#nav a’).hover(
function() {
$(this).addClass(‘hover’);
},
function() {
$(this).removeClass(‘hover’);
}
);
To make this snippet work, there are a few things you need to do. You must include JQuery in your <head>. I like to use Google Code to host it, like this.
<script language=”javascript” src=”http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js”></script>
Then put the code snippet that adds the hover class in a file. You could name it roll.js for example. Include this at the bottom of your document, inside the </body> and </html> end tags.
You may want to edit ‘ul#nav a’ to meet your personal needs. You can also change ‘hover’ to whatever class you prefer for the job.
The problem is that if you are like me, you use text replacement and your images are backgrounds. We need a way to preload the images or we see a delay on the first hover as the new background image loads.
I do this by simple creating a loop to iterate over the hovers in question. They activate quickly during page load so when the user puts their mouse over a button… no delay while the image loads. Nice.
Add this code snippet and make the appropriate changes to activate your hovers once during page load.
$(‘ul#nav a’).each(function() {
$(this).addClass(‘hover’);
}
);$(‘ul#nav a’).each(function() {
$(this).removeClass(‘hover’);
}
);