Jason T. Bedell
Jason T. Bedell

Reputation: 35

Use jQuery and Regex to Change All image SRC attributes?

I am working on a site with around 100 images. The images all have a light and a dark version. The light has the string _lt and the dark has the string _dk. I have code that works to change the image manually.

$('img#devbprnt').mouseover(function() {
$('img#devbprnt').attr('src', 'Images/btn_devbprnt_dk.png');    
});
$('img#devbprnt').mouseout(function() {
$('img#devbprnt').attr('src', 'Images/btn_devbprnt_lt.png');    
});

Ideally, what I would like to do is to use $('img') as the selector and any instances of _lt to _dk on mouseover, and do the reserve on mouseout. I think this might be possible with regex, but I don't understand them well enough. Is this possible? If so, can you help point me in the right direction?

Thank you, Jason.

Upvotes: 0

Views: 1121

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 219930

As pointed out by others, this should be done via CSS.

If for some reason that can't be done, here's how to do it in JavaScript:

$('img[src$="_lt.png"]').hover(function() {
    this.src = this.src.replace(/lt\.png$/, 'dk.png');
}, function() {
    this.src = this.src.replace(/dk\.png$/, 'lt.png');
});

Upvotes: 1

Andrew
Andrew

Reputation: 13853

jQuery also provides a hover() function to do this,

var dark = new RegExp('_dk$'),
    light = new RegExp('_lt$');
$('img').hover(function(){
   var image = $(this);
   image.attr('src', image.attr('src').replace(dark, '_lt'));
},
function(){
   var image = $(this);
   image.attr('src', image.attr('src').replace(light, '_dk'));
});

http://jsfiddle.net/qj5rw/

Upvotes: 1

Related Questions