Reputation: 437
How do I specify the exact file path directory for the "-hover" image (rollover effect)? Right now, this only works for images living in a child directory.
$(function(){
$('.box-img').append('<span></span>').hover(
function(){
$(this).find('img').stop().animate({opacity:0})
}, function(){
$(this).find('img').stop().animate({opacity:1})
}
).each(function(){
var src=new Array()
src=$(this).find('img').attr('src').split('.')
src=src[0]+'-hover.'+src[1]
$(this).find('>span').css({background:'url('+src+')'})
});
})
Upvotes: 2
Views: 1873
Reputation: 17471
I like to use sprites with the background-position
css property, but you can try this, using RegExp
:
$(document).ready(function(){
// Change the image of hoverable images
$(".imgHoverable").hover( function() {
var hoverImg = HoverImgOf($(this).attr("src"));
$(this).attr("src", hoverImg);
}, function() {
var normalImg = NormalImgOf($(this).attr("src"));
$(this).attr("src", normalImg);
}
);
});
function HoverImgOf(filename)
{
var re = new RegExp("(.+)\\.(gif|png|jpg)", "g");
return filename.replace(re, "$1-hover.$2");
}
function NormalImgOf(filename)
{
var re = new RegExp("(.+)-hover\\.(gif|png|jpg)", "g");
return filename.replace(re, "$1.$2");
}
Upvotes: 3
Reputation: 57388
You can use basename
from jquery.utils
to extract the basename from your src
. Then you split basename by ".", add '-hover', and reconstruct the path. So you needn't worry about names such as "../../css/images/image.png".
Or you can split by "/", then retrieve the last element of the array as the basename, and that one you split by ".".
var src=new Array()
// path/to/filename.jpg
src=$(this).find('img').attr('src').split('/')
var bname = src.pop() // bname is now filename.jpg, src is { path to }
var bco=new Array()
bco = bname.split('.') // bco is now { filename jpg }
ext = bco.pop() // ext is jpg, bco is { filename }
nam = bco.pop() // nam is filename, bco is { }
bco.push(nam + '-hover') // bco is { filename-hover }
bco.push(ext) // bco is { filename-hover jpg }
bname = bco.join('.') // bname is now filename-hover.jpg
src.push(bname)
srcString = src.join('/')
You also still have to care about how you name files with a dot in the basename (e.g. "ubuntu-12.02.jpg"), and how you reassemble the split array.
Upvotes: 1