Reputation: 11
In the following code, how do I adjust the code so that I can display more than 1 picture?
I am new to HTML.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Image Modal</h2>
<p>In this example, we use CSS to create a modal (dialog box) that is hidden by default.</p>
<p>We use JavaScript to trigger the modal and to display the current image inside the modal when it is clicked on. Also note that we use the value from the image's "alt" attribute as an image caption text inside the modal.</p>
<img id="myImg" src="img_fjords.jpg" alt="Trolltunga, Norway" width="300" height="200">
<!-- The Modal -->
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>
</body>
</html>
Upvotes: 1
Views: 3984
Reputation: 1036
My answer would be different depending on your purpose. So what do you need that for? Are you learing javascript? In production enviroment it would be easier and more prespective to use jquery lib.
Anyway. This is pure javascript solution. All you have to do is to distict image elements with selectors and copy event handles (.onclick).
<body>
<h2>Image Modal</h2>
<p>In this example, we use CSS to create a modal (dialog box) that is hidden by default.</p>
<p>We use JavaScript to trigger the modal and to display the current image inside the modal when it is clicked on. Also note that we use the value from the image's "alt" attribute as an image caption text inside the modal.</p>
<img id="myImg1" src="img_fjords.jpg" alt="Trolltunga, Norway" width="300" height="200">
<img id="myImg2" src="http://blog.tripwolf.com/de/blog/wp-content/uploads/2015/09/6059394277_55950beb55_b.jpg" alt="Trolltunga, Norway" width="300" height="200">
<!-- The Modal -->
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the images
var img1 = document.getElementById('myImg1');
var img2 = document.getElementById('myImg2');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
//handle click for myImg1
img1.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
//handle click for myImg2
img2.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";
}
</script>
</body>
Upvotes: 3