Home > Net >  Javascript: Store an image in an array by clicking the image in the gallery
Javascript: Store an image in an array by clicking the image in the gallery

Time:11-02

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

<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!";
 })
}

CodePudding user response:

Create an array. Use querySelectorAll() and its forEach() method 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.src in array
    if ( !selected_images.includes(src) ) {
      // 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=""  />
<img src=""  />
<img src=""  />
<img src=""  />
<img src=""  />

  • Related