I was working on a website project.
I saw an animation for images in w3schools.
I've tried it and it works perfectly well for just one picture--
// Get the modal
var modal = document.getElementById('myModal');
// Get the image and insert it inside the modal
var img = document.getElementById('a');
var modalImg = document.getElementById("img01");
img.onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
but i wanna use this for multiple images.
So i created a function like that:
function myBeautifulFunc(imageId, modalImageId) {
var modal = document.getElementById('myModal');
var img = document.getElementById(imageId);
var modalImg = document.getElementById(modalImageId);
img.onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
}
and called this function:
myBeautifulFunc('a', 'img01')
the result is:
it worked for the first image but when i tried it on second,
it looked like this: https://ibb.co/Mk8Xw1Z
I wanna show only one image when i clicked on it,
but it shows both of the images.
How can i solve this problem?
Your close function span.onclick = function()
is not hiding the children, so the second time you click, you are seeing the previous image and modalImage from the last time it was clicked.
function myBeautifulFunc(imageId, modalImageId) {
var modal = document.getElementById('myModal');
var img = document.getElementById(imageId);
var modalImg = document.getElementById(modalImageId);
img.onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
img.style.display = "none" // hide this also
modalImg.style.display = "none" // hide this also
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.