Struggling to create a fullscreen image modal on the web? I was able to get it working fine when embedding the script directly into my HTML file, but as soon as I moved it to an external JS file, things fell apart. I've double-checked all the variables and everything seems right. The issue might be with the function that displays the modal, but so far, no luck finding a solution. As a JavaScript beginner, any help would be greatly appreciated.
var modal = document.getElementById("myModal");
var img = document.getElementById("image01");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
.image {
cursor: pointer;
transition: 0.3s;
}
.image:hover {
opacity: 0.7;
}
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0 !important;
top: 0 !important;
width: 100% !important;
height: 100% !important;
overflow: auto !important;
background-color: rgb(0, 0, 0) !important;
background-color: rgba(0, 0, 0, 0.9) !important;
}
/* Modal Content (Image) */
.modal-content {
margin: auto;
display: block;
width: 100% !important;
max-width: 500px;
}
/* Caption of Modal Image (Image Text) - Same Width as the Image */
#caption {
margin: auto;
display: block;
width: 100%;
max-width: 500px;
text-align: center;
color: #ccc;
padding: 10px 0;
height: 150px;
}
/* Add Animation - Zoom in the Modal */
.modal-content,
#caption {
animation-name: zoom;
animation-duration: 0.6s;
}
@keyframes zoom {
from {
transform: scale(0)
}
to {
transform: scale(1)
}
}
/* The Close Button */
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771518180304030516073742594759475a1512031646">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<div class="row">
<div class="mb-3 row justify-content-center">
<div class="col-6 col-md-4 col-lg-3">
<div class="p-2"><img src="https://dummyimage.com/500" class="img-fluid image" id="image01" alt="Example">
</div>
</div>
</div>
</div>
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>