I have an API image gallery using Unsplash [https://codepen.io/aaron_1986/pen/WNybEmZ]; when I click to enlarge an image – the path of the src is missing. Moreover, I cannot understand how to enter the correct src path to enlarge the image.
//API CODE: let imageElement = document.querySelector('.image-box'); function loadImg(url) { let col = url.value; imageElement.innerHTML=''; for(let i=1; i < 10; i++) { let rand = Math.ceil(Math.random() * 8) * i let url = `<img src="https://source.unsplash.com/weekly?${col}%20${rand}">`; imageElement.insertAdjacentHTML('beforeend', url); } } //POPUP CODE: const images = [...document.querySelectorAll('.image-box')]; // popup const popup = document.querySelector('.popup'); const closeBtn = document.querySelector('.close-btn'); const largeImage = document.querySelector('.large-image'); images.forEach((item, i) => { item.addEventListener('click', () => { updateImage(i); popup.classList.toggle('active'); }) }) const updateImage = (i) => { let path = ``; largeImage.src = path; } closeBtn.addEventListener('click', () => { popup.classList.toggle('active'); })
<div class="popup"> <span class="close-btn"></span> <img src="" class="large-image" alt=""> </div> <div class="container images"> <div class="images section"> <div class="image-box"> <!-- images src code --> </div> <!-- image box -->
Advertisement
Answer
So basically your issue is the following:
Whenever you click on an image in order to enlarge it, you toggle the active
class on your div.popup
element which makes visible.
<div class="popup"> <span class="close-btn"></span> <img src="" class="large-image" alt=""> </div>
However you never set the src of the img
element inside your popup.
You could try adding an id to the img
tag inside your popup and setting the image src dynamically.
<div class="popup"> <span class="close-btn"></span> <img id="preview" src="" class="large-image" alt=""> </div>
images.forEach((item, i) => { item.addEventListener('click', (event) => { // get the `src` of the clicked image and pass it to the `openPreview` function const imageSource = event.target.src openPreview(i, imageSource); popup.classList.toggle('active'); }) }) const openPreview = (i, src) => { // let path = ``; largeImage.src = src; }
Link to codepen: https://codepen.io/lo1c/pen/bGKNmGr