Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

279
Visualizações
Passing the Id to get the element when Id is dynamic in javascript and php

I have this sample app in which small thumbnails are shown on screen fetched from database.

Requirement : When a thumbnail is click it should open in a modal as a large image, and each image should have its own download button when popped-up .

Issue - PHP is running fine, I can open image when clicked, but I don't have any clear thoughts on how to implement a download button for each image.

Note - I use prepared statements always but this is just a sample so I didn't used anything special.

Here is my code:

<?php   while($row = mysqli_fetch_assoc($result)){?>
    
    <img id="<?php echo $row['id'] ?>" src="<?php echo $row['img_name'] ?>" alt="">

<?php } ?>
<div id="myModal" class="modal">

  <!-- The Close Button -->
  <span class="close">&times;</span>

  <!-- Modal Content (The Image) -->
  <img class="modal-content" id="img">

  <!-- Modal Caption (Image Text) -->
  <div id="caption"></div>
</div>

This is my java script

    // Get the modal
let images = document.querySelectorAll(".imgwrap > img");

var modal = document.getElementById("myModal");
for(i=0; i<images.length; i++){
  let img = images[i];
  
  // Get the image and insert it inside the modal - use its "alt" text as a caption
  var modalImg = document.getElementById("img");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}
}
// 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";
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

To display the image on the modal you have to add event listeners to each of the thumbnails. That way you can display them on the modal or do whatever you want, when an it is clicked. I've created a working demo here Codepen. Please check it out.

HTML

<div class="images-wrapper">
  <?php while($row = mysqli_fetch_assoc($result)){?>
    
    <img class="gallery-img" id="<?php echo $row['id'] ?>" src="<?php echo $row['img_name'] ?>" alt="">

    <?php } ?>
</div>

<div class="modal" id="myModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-body" id="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" id="close-modal" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

JS

//select all thumbnails on the page generated by php
let images = document.querySelectorAll(".images-wrapper > img")

//loop over all the images and bind an eventlistener on click to each images 
for(i=0; i<images.length; i++){
  let img = images[i]
  img.addEventListener('click', showModal, false)
}

let modal = document.querySelector("#myModal")

function showModal(){
  
  //display mdodal
  modal.style.display = 'block'
  
  //select modal body element
  let modalBody = document.querySelector("#modal-body")
  
  //clear previously displayed image
  modalBody.innerHTML = ""
  
  //create an image element 
  let modalImg = document.createElement('img')
  modalImg.src = this.getAttribute('src')
  
  //create download btn
  let downloadBtn = document.createElement('a')
  // Create the text node
  let link = document.createTextNode("Download Image");
  downloadBtn.appendChild(link); 
  downloadBtn.href = this.getAttribute('src')
  downloadBtn.download = 'download'
  
  // add download btn 
  modalBody.prepend(downloadBtn)
  
  // add image element to modal body
  modalBody.appendChild(modalImg);
  
}

let closeBtn = document.querySelector("#close-modal")
closeBtn.addEventListener('click', closeModal, false)

//close modal
function closeModal(){
  modal.style.display = 'none'
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda