简体   繁体   中英

i'm not able to get modal box for my gallery images

I'm doing a dynamic site in php. This is the code of my gallery. I dont know what went wrong. I'm not able to get the modal box on clicking my gallery images. Can someone please help me?

 var modal = document.getElementsByClassName('myModal'); var img = document.getElementsByClassName('myImg'); var modalImg = document.getElementsByClassName("img01"); var captionText = document.getElementsByClassName("caption"); img.onclick = function() { modal.style.display = "block"; modalImg.src = this.src; captionText.innerHTML = this.alt; } var span = document.getElementsByClassName("close")[0]; // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } 
 <?php require_once("admin/config/connection.php"); $proname=""; $query1="select * from products_tb"; $resource1=mysql_query($query1,$connection); $result1=""; $id=""; while($record=mysql_fetch_array($resource1)) { $pid=$record['pid']; $img="uploads/".$record['proimg']; $proname=$record['proname']; $result1.="<div class='col-md-4 col-sm-4 mrgn_less prd'> <img style='width:300px;' id='myImg' class='modal-content' src='$img' '> <div class='myModal modal'> <span class='close'>&times;</span> <img class='modal-content img01' > <div class='caption'></div> </div> <br> </div>"; } ?> <?php echo $result1;?> 

Update your JavaScript code as below

var modal = document.getElementsByClassName('myModal');
var img = document.getElementsByClassName('myImg');
var modalImg = document.getElementsByClassName("img01");
var captionText = document.getElementsByClassName("caption");
img[0].onclick = function() {
  modal[0].style.display = "block";
  modalImg[0].src = this.src;
  captionText[0].innerHTML = this.alt;
}
var span = document.getElementsByClassName("close")[0];

when you use 'getElementsByClassName' it will return the object of html element So you need to use [0] to get the html element from that object.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM