Here’s my simple jQuery image rollover script.
View albertech-net-jquery-rollover.js Source
I modified it to work with absolute URLs. This works well if you have different servers hosting your image files. Adding image rollovers to your page is easy – just add class=”rollover” to your images.
$(function() {
$("#content .rollover").hover(function() {
// albertech.net rollover - get the extension of an absolute file path
var extensionLoc = ($(this).attr("src")).lastIndexOf(".");
var imgExtension = ($(this).attr("src")).substr(extensionLoc);
var hoverImage = ($(this).attr("src")).substr(0,extensionLoc) + "-hover" + imgExtension;
$(this).attr("src", hoverImage);
}, function() {
$(this).attr("src", $(this).attr("src").split("-hover.").join("."));
});
});
Usage:
1) Make a div with the id named “content”.
2) Add a class=”rollover” to the image.
3) Make two images — the second rollover one must have the same name as the first image with a -hover added to the end. For instance:
myimage.gif
myimage-hover.gif
The page should look something like: (simplified)
<html><head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#content .rollover").hover(function() {
// albertech.net rollover - get the extension of an absolute file path
var extensionLoc = ($(this).attr("src")).lastIndexOf(".");
var imgExtension = ($(this).attr("src")).substr(extensionLoc);
var hoverImage = ($(this).attr("src")).substr(0,extensionLoc) + "-hover" + imgExtension;
$(this).attr("src", hoverImage);
}, function() {
$(this).attr("src", $(this).attr("src").split("-hover.").join("."));
});
});
</script>
</head>
<body>
<div id="content">
<img class="rollover" src="myimage.gif" alt="" />
</div>
</body></html>
Pingback: Al