JQuery Image Switcher
I am using the image toggle feature in JQuery for a site I am building. There are many projects, so I compress a lot of these images a lot. Some of them, however, don't look pretty like .gifs, and it really makes sense to do a .jpg.
My problem is that this code only changes one image to another image of a different name but similar prefix. Is there a way to change the filename so that if I have a .gif or a .jpg it doesn't matter since it just replaces the name from _static with _rollover?
Here is the code I'm using:
//Image Switch
$(document).ready(function(){
$(".projectThumb img").hover(
function(){
var iconName = $(this).attr("src");
var origin = iconName.split("_static.")[0];
$(this).attr({src: "" + origin + "_rollover.gif"});
},
function(){
var iconName = $(this).attr("src");
var origin = iconName.split("_rollover.")[0];
$(this).attr({src: "" + origin + "_static.gif"});
});
});
and HTML for the image switcher
<div class="projectThumb">
<img src="/img/mr_button_static.gif" class="button" name="mr">
<p class="title">Title – Poster</p>
</div>
The displayed image is called /img/mr_button_rollover.jpg
Thank!
source to share
Just use string replacement to switch between static and rollover in the image name.
//Image Switch
$(document).ready(function(){
$(".projectThumb img").hover(
function(){
var iconName = $(this).attr("src");
var rollover = iconName.replace( /static/, 'rollover' );
$(this).attr({ src: rollover });
},
function(){
var iconName = $(this).attr("src");
var static = iconName.replace( /rollover/, 'static' );
$(this).attr({ src: static });
});
});
If there is a chance you could statically / overturn in the image prefix, just add an underscore to your search and replace lines and match / replace a dot before the file extension.
source to share