Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically replace img src attribute with jQuery

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

like image 868
jQuerybeast Avatar asked Sep 18 '11 14:09

jQuerybeast


People also ask

How to change image src dynamically using jQuery?

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.

How to update image in jQuery?

ready(function($) { $('#mybtn'). click(function() { $("productImageWrapID_16"). attr("src", "xyz. png"); }); });

How do I change my Onclick image in HTML?

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.


1 Answers

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); 
like image 55
Niko Avatar answered Oct 06 '22 00:10

Niko