Javascript - Execution multiple times

0

People, good afternoon

I have a JS + CSS code to open an image at normal size through a reduced image. I was able to do this with a single image, however, when I put a loop in php, an error occurs.

Follow below:

<-- Aqui deveria começar o loop em php -->

<img id="myImg" src="imagem_grande.jpg">

<div id="myModal" class="modal">
<span class="close"><img src="imagem_close.png"></span>
<img src="imagem_grande.png" class="modal-content" width="100%">  <div id="caption"></div>
</div>

<-- Aqui deveria fechar o loop em php -->

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

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

var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
modalImg.alt = this.alt;
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>

I have no practice in JS.

Thanks for the help!

Abs!

    
asked by anonymous 10.07.2016 / 20:56

1 answer

0

Probable errors are:

  • 1. Define the same attribute of id for each image and modal.
  • 2. Modify only one image and one modal.
  • 3. You are not traversing all created images and modals.

To make your code work you will need to modify the HTML. Create a container and place the image and modal within it. Add a class to the image of the varied execution, and also to some modal elements. For simplicity:

<div class="row">
    <img class="my-img" src="imagem_grande.jpg"/>
    <div class="modal">
        <span class="close-btn">
            <img src="imagem_close.png"/>
        </span>
        <img src="imagem_grande.png" class="modal-content" width="100%">
        <div class="caption"></div>
    </div>
</div>

. Now, test this with JavaScript:

var rows = document.getElementsByClassName("row");

/** ... Iterate each row with image and modal **/
for(var i = 0, row; row = rows[i]; i ++) {
    /* The big image */
    var myImg = row.getElementsByClassName("my-img")[0];
    /* Modal elements */
    var modal = row.getElementsByClassName("modal")[0];
    var modalCaptionText = modal.getElementsByClassName('caption')[0],
        modalCloseBtn = modal.getElementsByClassName('close-btn')[0],
        modalImg = modal.getElementsByTagName('img')[0];

    myImg.onclick = function() {
        modal.style.display = 'block';
        modal.src = this.src;
        modalImg.alt = this.alt;
        modalCaptionText.innerHTML = this.alt;
    };

    // When the user clicks on <span> (x), close the modal
    modalCloseBtn.onclick = function() {
        modal.style.display = "none";
    };
}
    
10.07.2016 / 22:04