jquery for loop on click image swap

Posted by user2939914 on Stack Overflow See other posts from Stack Overflow or by user2939914
Published on 2013-10-31T03:48:12Z Indexed on 2013/10/31 3:53 UTC
Read the original article Hit count: 141

Filed under:
|
|
|
|

I've created a for loop of images. I would like each image to swap with another image on click individually. Here's the jQuery I've written so far:

for ( var i = 1; i < 50; i++) {
  $('article').append('<div class="ps-block" id="' + i + '"><img src="img/bw/' + i +   'bw.png"></div>');
}

$('img').click(function() {
  var imgid = $(this).attr('id');
  $(this).attr("src", "img/color/" + imgid + ".png");    
});

I also attempted to use this code inside the for loop after the append, but i ends up returning 50 every time you click since the loop has already ran:

$('img[src="img/bw/' + i + 'bw.png"]').click(function() {
    $(this).attr("src", "img/color/" + this.id + ".png");    
});

Thanks!

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about image