Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

multiple images gallery after clicking image javascript

const data=[["https://dummyimage.com/100x100/ad40ad/000000","https://dummyimage.com/100x100/454545/000000","https://dummyimage.com/100x100/789acc/000000","https://dummyimage.com/100x100/994563/000000","https://dummyimage.com/100x100/fff456/000000"],["https://dummyimage.com/100x100/ad40ad/000000","https://dummyimage.com/100x100/454545/000000","https://dummyimage.com/100x100/789acc/000000","https://dummyimage.com/100x100/994563/000000","https://dummyimage.com/100x100/fff456/000000"]];

// Returns a new array of images from
// the source array
function loadImageSet(arr) {
  return new Promise(res => {
    const set = arr.map(src => {
      const img = new Image();
      img.src = src;
      return img;
    });
    res(set);
  });
}

// Returns a nested array of images
function preload(data) {
  return Promise.all(data.map(loadImageSet));
}

async function main(data) {
  
  // Get the images
  const images = await preload(data);

  // Cache the containers
  const containers = document.querySelectorAll('div');

  // For each container add a listener. `handleClick`
  // does some initial setup (using the id, and image set),
  // and then returns a new function that is called
  // when `click` is triggered
  containers.forEach(c => {
    const { id } = c.dataset;
    const imageSet = images[id - 1];
    c.addEventListener('click', handleClick(c, id, imageSet), false);
  });

};

// Call the main function
main(data);

// Accepts an id and an image set
function handleClick(container, id, imageSet) {

  // Initialises the array index
  let index = 0;

  // Initialises the first image
  container.appendChild(imageSet[index]);
  
  // Increases the index
  ++index;

  // Return the function that is called when
  // the click event is triggered
  return function () {

    // Reset `index` if it hits the `imageSet` length
    if (index === imageSet.length) index = 0;

    // Replace the image with the next one in
    // in the `imageSet` array
    const img = container.querySelector('img');
    img.replaceWith(imageSet[index]);

    // Finally increase `index`
    ++index;
  }

}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #multiple #images #gallery #clicking #image #javascript
ADD COMMENT
Topic
Name
5+5 =