Replace img attribute only works first time

212 views Asked by At

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!

3

There are 3 answers

0
Phil On

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.

0
ericjbasti On

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);
0
jick On

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

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