MultiDev
MultiDev

Reputation: 10649

Using jQuery to change image source URL

I have two images, one transparent:

http://www.example.com/image-trans.png

And another one with a background:

http://www.example.com/image.png

I am trying to use jQuery to change the src of the image from image-trans.png (original value) to image.png when a certain event is triggered.

I am able to accomplish this by typing the src directly into my jQuery code:

$("img.nav51").attr("src","http://example.com/image.png");

However, I am trying to do this without typing the URL directly into my jQuery, as the URL is dynamically set elsewhere, and is subject to change.

Here is what I am trying, but it does not do anything for me:

$('img.nav51').attr("src").replace("-trans.png", ".png");

Any suggestions?

Upvotes: 2

Views: 121

Answers (3)

Spokey
Spokey

Reputation: 10994

$('img.nav51').attr('src', function(){ 
     return this.src.replace("-trans.png", ".png"); 
});

Upvotes: 0

Kevin Labécot
Kevin Labécot

Reputation: 1995

To set/update the attribute you must pass the new value in the second parameter.

Try this :

var originalSrc = $('img.nav51').attr("src");
$('img.nav51').attr("src", originalSrc.replace("-trans.png", ".png"));

Upvotes: 4

Vennik
Vennik

Reputation: 565

You have to set it to replace it:

$('img.nav51').attr("src", $('img.nav51').attr("src").replace("-trans.png", ".png"));

Upvotes: 1

Related Questions