A lazy/better JQuery way to do CSS Image Rollovers
When it comes to development, I’m a firm believer that laziness is a virtue. If I can write code to do what I need done in as little lines as possible, not only am I doing less typing, but my code is probably going to be more efficient (either that or it’s going to be really hacky).
In the course of web design, I find myself coding rollover images often. I’m a big fan of pure CSS image rollovers, which are quicker to load and don’t deal with JavaScript. However, if you’re dealing with many links that all need a rollover, your css quickly becomes bloated.
JQuery to the rescue!
So I’ve put together this little script:
-
$(document).ready(function(){
-
$(‘.hoverlinks’).each(function(){
-
var img_name=$(this).attr(‘title’);
-
$(this).css({"background": "url(‘"+img_name+"_mouseover.png’) no-repeat left bottom"});
-
$(this).hover(
-
function(){
-
$(this).css({"background-position" : "right bottom"});
-
},
-
function(){
-
$(this).css({"background-position" : "left bottom"});
-
});
-
});
-
-
});
The advantage to this script is that it uses the title attribute of an element to look up whatever your rollover image is called. For example, all you need is
And a corresponding “mylink_mouseover.png” to dynamically generate a CSS rollover. You must name your images to match the contents of the title attribute (plus the “_mouseover.png” syntax or whatever you decide to call it in the JavaScript).
You’ll need, of course, to do some styling on the rollover class and it’s parent elements (or wherever), but you won’t find yourself in a soup of
background:url(“home.png”)no-repeat right bottom;
}
#home-link:hover{
background-position:left bottom;
}
#back-link{
background:url(“back.png”) no-repeat right bottom;
}
#back-link:hover{
background-position:left bottom;
}
and so on…..
The script works by going through each member of the hoverlinks class and getting the contents of the title attribute, thanks to .attr(). Then, the background is set dynamically though JQuery’s .css() function. This will throw in a “style” attribute in your HTML, the HTML should still validate.
Then, a call to JQuery’s .hover() keeps track of mouseOver events and calls .css() to move the background image around accordingly.
I hope this is useful, I am currently using it in a Drupal project I’m working on.
No comments yet.