Sven
Sven

Reputation: 13296

Dynamically changing source of image - jQuery

I got the following code:

HTML

<div class="image">
    <img src="http://ecx.images-amazon.com/images/I/41ghiuvjdvL._SL75_SS50_.jpg" />
</div>

<br />

<div class="photo">
    <img src="http://profile.ak.fbcdn.net/hprofile-ak-ash2/27520_119569768054263_2432_q.jpg" />
</div>​

JS

// getting src of bottom image
var bottomSrc = $(".photo img").find("src");

// getting src of top image
var topSrc = $(".image img").find("src");

$(".photo").click(function() {
    // changing sources
    // topSrc.attr("src", bottomSrc);
    // topSrc.replaceWith(bottomSrc);
    topSrc.replace(bottomSrc);
})​

Fiddle

When the bottom image is clicked, I want the src of the top image to be replaced with the bottom image's src, so that both images are the same.

Why does the supplied code does not work?

Upvotes: 0

Views: 1583

Answers (2)

jose
jose

Reputation: 2543

Try this

You need to get and set the src attribute, using attr() function in jQuery

Upvotes: 0

Tim Withers
Tim Withers

Reputation: 12069

Try this out:

$(".photo").click(function() {
    var src=$(this).children("img").attr("src");
    $(".image img").attr("src",src);
})​;

Upvotes: 4

Related Questions