jick
jick

Reputation: 168

Replace img attribute only works first time

So I have this jQuery function:

$('ul li').click(function () {
    var title = $('img', this).attr("title");
    $("a.songtitle span").text(title);

    var artist = $('img', this).attr("artist");
    $("a.songartist span").text(artist);

    var artwork = $('img', this).attr('src');
    artwork = artwork.replace('src');

    $('img.a').attr('src', artwork);
    $(this).addClass('playing').siblings().removeClass('playing');

    audio.load($('a#tunes', this).attr('data-src'));
    audio.play();
});

So, when clicked, it gets album artwork from an img src attribute and replaces it with the current. As you can see in this example, it's only working the first time, and then no longer replaces the img src attribute when you click on "Next". Why is this happening? If someone can help that would be greatly appreciated. Thank you!

Upvotes: 1

Views: 212

Answers (3)

jick
jick

Reputation: 168

I seem to have figured it out. I fixed it by doing:

$('img.a:first').attr('src', artwork);

Upvotes: 0

ericjbasti
ericjbasti

Reputation: 2075

If you run your code and then, run this line in your inspector/console:

$('img.a');

You'll see you've changed every image to the exact same source. You should look into giving the item displaying this information a unique ID, so you can start calling it with something like this:

$('#myID img').attr('src',artwork);

Upvotes: 0

Phil
Phil

Reputation: 164742

This line

$('img.a').attr('src', artwork);

is replacing the src attribute value for all images with class a.

Also, you're missing the second argument to replace() on this line

artwork = artwork.replace('src');

lucky for you, it's not doing anything unless the string "src" appears in the image URL.

Upvotes: 1

Related Questions