Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript: Store an image in an array by clicking the image in the gallery

I need to solve the following steps: store image(s) in array for later use. I am really experiencing difficulties I don’t know where to start.

I have created a small gallery using picsum; when the user clicks on an image; the image needs to be stored in a new array [of images].

https://codepen.io/aaron_1986/pen/oNyborW?editors=1010

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<img src="" id="ggg">
<img src="" id="ggg">
<img src="" id="ggg">
<img src="" id="ggg">
<img src="" id="ggg">
<div id="text">
</div>

JS

for(let i = 0; i < 5; i++) {
  const img = document.getElementById("ggg");
  img.src = "https://picsum.photos/200/301?id=" + i;
  document.body.appendChild(img);

  img.addEventListener("click", function() {
  console.log(i); 
  document.getElementById("text").innerHTML = "YOU CLICKED ME!";
 })
}

>Solution :

Create an array. Use forEach() to loop over IMG elements. Update img.src. Use addEventListener() to add img.src to array when an image is clicked. Give user feedback.

let selected_images = [];
document.querySelectorAll('.ggg').forEach(function (img, idx) {
  img.src = "https://picsum.photos/200/301?id=" + idx;

  img.addEventListener("click", function({target: src}) {
  
    // check for existing img in array
    !selected_images.includes(src) // don't terminate (;) this expression
    
    // append to array if not found
    && selected_images.push(src);
    
    document.getElementById("text").innerHTML = `YOU CLICKED ${idx + 1}`;
    console.log(selected_images);
  });
});
<div id="text">&nbsp;</div>
<img src="" class="ggg" />
<img src="" class="ggg" />
<img src="" class="ggg" />
<img src="" class="ggg" />
<img src="" class="ggg" />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading