Home » Javascript » Modal images to change on keyboard arrow click

Modal images to change on keyboard arrow click

Posted by: admin August 19, 2018 Leave a comment

Questions:

I have flexbox Image grid in my portfolio and when I click any of the images, the modal image pops up in front of the page, but I want to be able to change the images at this pop up window without closing it. This is my code:

HTML:

<div class="row"> 
<div class="column">
<img src="../content/images/Photography/1.jpg" style="width:100%" 
class="myImg" alt="Жоркатааа">
<img src="../content/images/Photography/2.jpg" style="width:100%" 
class="myImg">
<img src="../content/images/Photography/3.jpg" style="width:100%" 
class="myImg">
<img src="../content/images/Photography/4.jpg" style="width:100%" 
class="myImg">
</div>

<div class="column">
<img src="../content/images/Photography/12.jpg" style="width:100%" 
class="myImg" alt="Жоркатааа">
<img src="../content/images/Photography/22.jpg" style="width:100%" 
class="myImg">
<img src="../content/images/Photography/13.jpg" style="width:100%" 
class="myImg">
<img src="../content/images/Photography/14.jpg" style="width:100%" 
class="myImg">

</div>  
<div class="column">
 <img src="../content/images/Photography/32.jpg" style="width:100%" 
class="myImg" alt="Жоркатааа">
<img src="../content/images/Photography/45.jpg" style="width:100%" 
class="myImg">
<img src="../content/images/Photography/23.jpg" style="width:100%" 
class="myImg">
<img src="../content/images/Photography/24.jpg" style="width:100%" 
class="myImg">    
</div>  
</div>  
</div>  

<div id="myModal" class="modal">
<span class="close">&times;</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>

JAVASCRIPT:

<script>
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a 
caption
var imgs = document.getElementsByClassName('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");

for (var i = 0; i < imgs.length; i++) {
imgs[i].addEventListener('click', e => {
  modal.style.display = "block";
  modalImg.src = e.target.src;
  captionText.innerHTML = e.target.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";
}

document.onkeyup = function (e) {
e = e || window.event;

// 27 is the ESC key
if(e.keyCode === 27) modal.style.display = "none";
};
</script>

I am not really good at javascript, s I hope you can help me with putting the additional code in the existing code. Thank you!

Answers: