AndrewLeonardi
AndrewLeonardi

Reputation: 3512

How to handle: When image is clicked identical image generated using Javascript

The code below works to make one copy of the image clicked. I am needing the code below to work for multiple images.

For example if I click 5 images on the screen, the same 5 images should generate at the bottom of the page. The user should be able to select 5 out of 10 images. Any thoughts? Thanks!

JS:

function changeImage() {
      var imgSrc = 'http://placehold.it/150';

      if (document.getElementById('myImage').src === imgSrc) {
        document.getElementById('new').src = imgSrc;
      }
    }

HTML

<a href="#" onClick="changeImage()">
  <img id="myImage" src="http://placehold.it/150"></a>
<img id="new" src="http://placehold.it/200">

Upvotes: 1

Views: 33

Answers (2)

Nenad Vracar
Nenad Vracar

Reputation: 122077

You can use JQuery clone() function

$('img').click(function() {
  $('body').append($(this).clone());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://placehold.it/50x50">
<img src="http://placehold.it/50x50/000000/ffffff">
<img src="http://placehold.it/50x50/1C90F3/ffffff">
<img src="http://placehold.it/50x50/F2BB7C/ffffff">

Upvotes: 1

Senad Meškin
Senad Meškin

Reputation: 13756

you can use jquery to do that

HTML

<a href="#" id="my-image">
  <img id="myImage" src="http://placehold.it/150"></a>
<img id="new" src="http://placehold.it/200" />

JS

$('#my-image').click(function(){
   //setting attribute src to be equal as src from #myImage
   $('#new').attr('src', $('#myImage').attr('src'));
   //returning false in order to avoid default action
   return false;
});

So that is it :)

Just remember to put this code after your html or into

$(document).ready(function(){ ..... });

I hope this helps.

Upvotes: 0

Related Questions