0

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.

3
  • 4
    Why don't you use CSS for this, is it just a hover effect? Commented Aug 1, 2012 at 16:51
  • 1
    rather than having light and dark versions of images, you might consider appending an element on top of the image and then setting transparency of the element. Not sure if this will work for whatever you're doing, but it's certainly more efficient Commented Aug 1, 2012 at 16:52
  • 2
    Another thing is that if you need to select them you can use $('img[src$="_lt.png"]') and $('img[src$="_dk.png"]') Commented Aug 1, 2012 at 16:55

2 Answers 2

1

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');
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks everyone. These answers got me really close. I really appreciate it. What seemed to finally work was: $('img').mouseover(function() { var src = $(this).attr('src'); src = src.replace("_lt", "_dk"); $(this).attr('src', src); }); $('img').mouseout(function() { var src = $(this).attr('src'); src = src.replace("_dk", "_lt"); $(this).attr('src', src); });
1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.