How to use for in Javascript to view photo gallery

Asked

Viewed 108 times

-1

So, I’m still pretty weak on javascript.. I’m looking to learn more.

It is a very simple code, are two "div", div thumbnail and maximized div, my CSS code displays in a floating banner the maximized div when I click on one of the li inside the .

But it only displays the last image from the list. I don’t know how to structure my being in a way that shows precisely the cliacada image in li.

I tested the code without using the structure for and it worked, but I need the for because I will work with several images.

This is my javascript:

<script>
$(function(){
    $('.sairFoto').click(function(){
        $('#maximizada').fadeOut(500);
    });
    $('#miniatura ul li').click(function(){
        $('#maximizada').fadeIn(500);
    }); 

    for(var i = 1; i < 100; i++){
        $('.foto'+ i ).click(function(){
            document.getElementById("imgMax").src = "fotos/img"+ i +".jpg"; 
        });         
    };
});
</script>


<div id="galeria">
    <div id="maximizada">
        <div class="sairFoto">X</div>
        <img id="imgMax" src="fotos/img1.jpg" />        
    </div>

    <div id="miniatura">
            <ul>
                <li><img src="fotos/img1.jpg" class="foto1" /></li>
                <li><img src="fotos/img2.jpg" class="foto2" /></li>
                <li><img src="fotos/img3.jpg" class="foto3" /></li>
                <li><img src="fotos/img4.jpg" class="foto4" /></li>
                ....

                <li><img src="fotos/img100.jpg" class="foto100"/></li>          
            </ul>           

    </div>

</div>

1 answer

0


The problem is that when you create the event of each element, the variable i inside the function is the same used inside the loop for.

This means that at the end of the repetition structure, the variable will have in all functions the last value that in the case is 99. See the example below to better understand:

for (let i = 0; i < 10; i++) {
    function show_number() {
        // A variável "i" é a mesma que "i" do laço for. 
        // Logo, a variável aqui dentro sofrerá alterações.
        console.log(i); 
    }
}

show_number();

What you can do is get the element you clicked on using $(this), in order to achieve the attribute src of the element itself. See how the code would look:

for (var i = 1; i < 100; i++) {
    $('.foto' + i ).click(function() {
        const src = $(this).attr("src");
        document.getElementById("imgMax").src = src; 
    });         
}

  • 1

    Shooow ! Thank you very much for your reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.