adding previous/next slide event listeners for modal lightbox (Javascript)

  css, html, javascript, lightbox, modal-dialog

I’m building a portfolio site for a friend which displays paintings. All paitings are displayed on the index page, and I’ve created a for loop so that click on each painting opens up modal displaying that painting:

// create references to the modal...
const modal = document.getElementById('myModal');
// to all images -- note I'm using a class!
const images = document.getElementsByClassName('myImages');
// the image in the modal
const modalImg = document.getElementById("img01");
// and the caption in the modal
const captionText = document.getElementById("caption");


// Go through all of the images with our custom class
for (let i = 0; i < images.length; i++) {
  let img = images[i];
  // and attach our click listener for this image.
  img.addEventListener("click", openModal)
}

// Function to open modal
function openModal() {
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

I’ve attached previous and next buttons to the modal, and I’d like to be able to go back and forth between paintings once the modal is open:

<!-- The Modal -->
  <div id="myModal" class="modal">
  <!-- The Close Button -->
  <span class="close" onclick="document.getElementById('myModal').style.display='none'">&times; 
  </span>
  <!-- Modal Content (The Image) -->
  <img class="modal-content" id="img01">
  <!-- Modal Caption (Image Text) -->
  <div id="caption"></div>

  <a class="prev">❮</a>
  <a class="next">❯</a>
</div>

I’m trying to add event listeners to the prev/next buttons however am running into trouble – I’m not sure how to access the selected image from the modal so it knows to open the previous/next one when prev/next buttons are clicked.

// selecting the prev and next buttons
const prev = document.querySelector(".prev")
const next = document.querySelector(".next")

prev.addEventListener("click", previousSlide);

function previousSlide() {
  // Not sure what to put here...
}

Can anyone help me out or at least point me in the right direction? Thanks

Source: Ask Javascript Questions

LEAVE A COMMENT