Matt Ellis Matt Ellis - 7 days ago 4x
HTML Question

How can I update image in bootstrap modal using javascript?

So I have multiple images in a photo gallery of sorts and want to be able to click on the image and in doing so it opens the bootstrap modal with the image I clicked on.

I think the way to do it is when the image is clicked, take the image source and apply it to the modal image source.

Here is my Html:

<!-- Example Trigger image-->
<div class="col-md-3 galleryImg">
<a href="#myModal" role="button" data-toggle="modal"><img onclick="myfunction(this)" class="galleryImage" src="img/H1.jpg"></a>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">Image</h4>
<div class="modal-body">
<img id="modalImage" src="img/H1.jpg">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Here is my javascript:

function myfunction() {
var initialSrc = img.src;
document.getElementById("modalImage").src = initialSrc;}


You forgot the img parameter:

function myfunction(img) {
    var initialSrc = img.src;
    document.getElementById("modalImage").src = initialSrc;