tags:

views:

41

answers:

1

I am looking for some easy jquery solution for hover images.

Like if i define a class. them jquery should get the current image like

abc.png then chnage that to abc_on.png

and then put that to on hover image

How can i do that.

i don't want to add function for every button.

Just one function and it do all.

My Images all usually imagename.png or imagename_on.png

+4  A: 
$('img.class').hover(function() {
   var obj = $(this); 
   obj.attr('src', obj.attr('src').replace('.png', '_on.png'));
}, function () {
   var obj = $(this); 
   obj.attr('src', obj.attr('src').replace('_on.png', '.png'));
});

I haven't had a chance to try it, but it should work, as long as .png does not show up in the filename elsewhere.

Edit: A solution that is a little more expensive using regular expressions:

var onRe = new RegExp('\\.(.*)$');
var offRe = new RegExp('_on\\.(.*)$');
$('img.class').hover(function() {
   var obj = $(this);
   obj.attr('src', obj.attr('src').replace(onRe, '_on.$1'));
}, function () {
   var obj = $(this);
   obj.attr('src', obj.attr('src').replace(offRe, '.$1'));
});
halkeye
you should avoid selecting `$(this)` twice. you could use $that = $(this) and then youe $that.attr() etc..
meo
I was feeling a little lazy for the example, but you are right, I've updated the code.
halkeye
that was good but can you please chnage the code that if the image extension can be any like gif, jpg etc, then it shoulk also work
Mirage
Updated answer to add one that should work with any extension type. I would suggest next time to include that kind of info in your question, yours just asked about png
halkeye
thanks buddy , that worked
Mirage