I am trying to replace the img source of a given source using jQuery. For example, when the image src is smith.gif, replace to johnson.gif. If williams.gif replace to brown.gif etc.
EDIT: The images are retrieved from an XML to a random order, without class to each .
This is what I tried:
if ( $("img").attr('src', 'http://example.com/smith.gif') ) { $(this).attr('src', 'http://example.com/johnson.gif'); } if ( $("img").attr('src', 'http://example.com/williams.gif') ) { $(this).attr('src', 'http://example.com/brown.gif'); }
Note that my HTML has many images. For example
<img src="http://example.com/smith.gif"> <img src="http://example.com/williams.gif"> <img src="http://example.com/chris.gif">
etc.
So, how can I replace the images: IF img src="http://example.com/smith.gif" then show "http://example.com/williams.gif". etc...
Thanks alot
Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.
ready(function($) { $('#mybtn'). click(function() { $("productImageWrapID_16"). attr("src", "xyz. png"); }); });
The most you could do is to trigger a background image change when hovering the LI. If you want something to happen upon clicking an LI and then staying that way, then you'll need to use some JS. I would name the images starting with bw_ and clr_ and just use JS to swap between them.
This is what you wanna do:
var oldSrc = 'http://example.com/smith.gif'; var newSrc = 'http://example.com/johnson.gif'; $('img[src="' + oldSrc + '"]').attr('src', newSrc);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With