Skip to main content
AmySykes
Known Participant
September 10, 2023
Answered

How do I use Javascript to loop or cycle through and array of images on one increment per click?

  • September 10, 2023
  • 5 replies
  • 7828 views
    This topic has been closed for replies.
    Correct answer osgood_

    Happy Monday!!

    If this was written out the long way without arrow functions how would that look?

    images.forEach(function(img) {
    img.onclick = function() {
    images.forEach((img) => {
    img.classList.remove('active')
    })
    if(count === 0) {
    count = 0;
    }
    else {
    count--;
    }
    images[count].classList.add('active');
    }
    })


    quote

    Happy Monday!!

    If this was written out the long way without arrow functions how would that look?

    images.forEach(function(img) {
    img.onclick = function() {
    images.forEach((img) => {
    img.classList.remove('active')
    })
    if(count === 0) {
    count = 0;
    }
    else {
    count--;
    }
    images[count].classList.add('active');
    }
    })


    By @AmySykes

     

     

    NOT a great deal of difference:

     

    NO ARROW FUNCTION VERSION:

     

    images.forEach(function(img) {
    img.onclick = function() {
    images.forEach(function(img) {
    img.classList.remove('active')
    })
    if(count === 0) {
    count = 0;
    }
    else {
    count--;
    }
    images[count].classList.add('active');
    }
    })

     

     

    ARROW FUNCTION VERSION:

     

    images.forEach((img) => {
    img.onclick = () => {
    images.forEach((img) => {
    img.classList.remove('active')
    })
    if(count === 0) {
    count = 0;
    }
    else {
    count--;
    }
    images[count].classList.add('active');
    }
    })

     

     

     

    YOU COULD SHORTEN THE CODE MORE BY USING THE TERNARY OPERATOR (IN BOLD) AS A REPLACEMENT FOR the IF/ELSE BLOCK:

     

    images.forEach(function(img) {
    img.onclick = function() {
    images.forEach(function(img) {
    img.classList.remove('active')
    })
    count === 0 ? count = 0: count--;
    images[count].classList.add('active');
    }
    })

    5 replies

    AmySykes
    AmySykesAuthor
    Known Participant
    September 18, 2023

    How do we attach an event listener to the image object? and get the image carousel to scroll backward? The demo video is attached along with the coding.

    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Click Through Images</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
    <style>
     
    .col:first-child {
        background-color: grey;
        height: 100vh;
        z-index: 1;
        transition: all .5s ease-in-out;
    }
    button {
        width: 250px;
        height: 80px;
    top: 40vh;
        position: relative;
        background-color: transparent;
    }
    span {
        width: 0px;
        height: 78px;
        position: absolute;
        left: 0;
        top: 0;
        background-color: white;
        z-index: -1;
        transition: all .5s ease-in-out;
    }
    button:hover span {
        width: 248px;
    }
    .gallery {
    /*width: 70%;*/
    margin: 0 auto;
    }
    .largeImg {
    display: grid;
    grid-template-columns: 1fr;
    }
    .largeImg img {
    max-width: 100%;
    display: none;
    }
    .largeImg img.active {
    display: block;
    height: 100vh;
    animation: fadeIn .5s forwards ease-in-out;
    }
    .swapImg {
    display: block;
    margin: 25px auto;
    }
    @14668356 fadeIn {
    0% {
    opacity: 0;
    transform: translatex(-840px);
    height: 840px;
     
    }
    100% {
    opacity: 1;
    width: 840px;
    transform: translatex(0px);
    }
    }
    </style>
    </head>
    <body>
    <div class="container-fluid text-center">
      <div class="row">
        <div class="col">
          <button type="button" class="swapImg"><span></span>Swap Image</button>
        </div>
        <div class="col-6 m-0 p-0 gallery" style="background-color: #c44646">
            <div class="largeImg">
    <img id="abc" src="img/quiz.gif" alt="" width="0px" height="100vh" class="active">
            <img src="img/quiz1.gif" alt="" width="0" height="100vh">
            <img src="img/quiz2.gif" alt="" width="0" height="100vh">
            <img src="img/quiz3.gif" alt="" width="0" height="100vh">
            <img src="img/quiz4.gif" alt="" width="0" height="100vh">
    <img src="img/quiz5.gif" alt="" width="0" height="100vh">
    <img src="img/quiz6.gif" alt="" width="0" height="100vh">
            <img src="img/quiz7.gif" alt="" width="0" height="100vh">
    <img src="img/quiz8.gif" alt="" width="0" height="100vh">
            </div>
        </div>
        <div class="col" style="background-color: #313030"> Column</div>  
      </div>
    </div>
    <script>
        const images = document.querySelectorAll('.largeImg img');
        const swapImg = document.querySelector('.swapImg')
    console.log(swapImg); 
     
     
     
    let count = 0;
     
     
    swapImg.addEventListener('click', () => {//button
    count++; 
    images.forEach((img) => {//for each img item in the node list?
    img.classList.remove('active')
    })
     
    if(count === images.length) {
    count = 0;
    }
     
     
    images[count].classList.add('active');
    });
     
     
    </script>
    </body>
    </html>

     

    Brainiac
    September 18, 2023
    quote

    How do we attach an event listener to the image object? and get the image carousel to scroll backward? The demo video is attached along with the coding.

     

    By @AmySykes

     

    Add the below javascript directly before the closing </script> tag:

     

    images.forEach(function(img) {
    img.onclick = function() {
    images.forEach((img) => {
    img.classList.remove('active')
    })
    if(count === 0) {
    count = 0;
    }
    else {
    count--;
    }
    images[count].classList.add('active');
    }
    })
    AmySykes
    AmySykesAuthor
    Known Participant
    October 2, 2023
    quote

    Happy Monday!!

    If this was written out the long way without arrow functions how would that look?

    images.forEach(function(img) {
    img.onclick = function() {
    images.forEach((img) => {
    img.classList.remove('active')
    })
    if(count === 0) {
    count = 0;
    }
    else {
    count--;
    }
    images[count].classList.add('active');
    }
    })


    By @AmySykes

     

     

    NOT a great deal of difference:

     

    NO ARROW FUNCTION VERSION:

     

    images.forEach(function(img) {
    img.onclick = function() {
    images.forEach(function(img) {
    img.classList.remove('active')
    })
    if(count === 0) {
    count = 0;
    }
    else {
    count--;
    }
    images[count].classList.add('active');
    }
    })

     

     

    ARROW FUNCTION VERSION:

     

    images.forEach((img) => {
    img.onclick = () => {
    images.forEach((img) => {
    img.classList.remove('active')
    })
    if(count === 0) {
    count = 0;
    }
    else {
    count--;
    }
    images[count].classList.add('active');
    }
    })

     

     

     

    YOU COULD SHORTEN THE CODE MORE BY USING THE TERNARY OPERATOR (IN BOLD) AS A REPLACEMENT FOR the IF/ELSE BLOCK:

     

    images.forEach(function(img) {
    img.onclick = function() {
    images.forEach(function(img) {
    img.classList.remove('active')
    })
    count === 0 ? count = 0: count--;
    images[count].classList.add('active');
    }
    })


    Thank-you. Have a happy night.

    AmySykes
    AmySykesAuthor
    Known Participant
    September 12, 2023

    Dear Adobe

    Lena's, Comments are correct and were the initial reply. Please fix what she is saying needs to be fixed so she gets all the credit she deserves.  Lena Thank you for all your help. You are a complete Rockstar.

     

    Brainiac
    September 12, 2023

    Folks there's no one correct answer here, all the suggestions and solutions are constructive and could be put to good use. Stop fretting about it, there is more to life than missing out on a couple of brownie points.

    AmySykes
    AmySykesAuthor
    Known Participant
    September 13, 2023

    Osgood Thank you for all your help. Your answer was correct as well. Your suggestions were constructive and were put to good use as well. Thank you for helping me. I could not have done it alone. 

     

    Community Expert
    September 11, 2023

    Your approach is also a nice solution, but it's double-edged...

     

    The advantage is that all images are preloaded, so there's no need to wait after clicks to advance, but without taking this large preloading into account, you'll have to wait before you can start interacting, especially if there are a lot of images!

     

    The disadvantage is that if the user doesn't click on the button, the non displayed images will have been loaded for nothing.

     

    But class permutation is elegant.

    Brainiac
    September 11, 2023
    quote

    Your approach is also a nice solution, but it's double-edged...

     

    By @L e n a

     

    Yep, it's really aimed at those that have not yet progressed to a more advanced level of implementing  a workflow using arrays which bring another dimension to the party. It might also be useful in terms of a limited amount of images being used in an auto rotating hero section. I'd consider having some kind of fade in effect on the images rather than just suddenly appearing, it adds a bit of a smoother result.

    Brainiac
    September 10, 2023

    You already have a good reply as a solution but I'll throw this one into the mix just incase arrays like the following = const images = ['blah' , 'blah' , 'blah'] are a bit daunting to you.

     

    You can still hard code the images into the html as you may usually do and then use css to hide them and javascript to create an array from them, just add your own images, instead of image_1.jpg, image_2.jpg etc:

     

     

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Click Through Images</title>
    
    <style>
    .gallery {
    width: 70%;
    margin: 0 auto;
    }
    .largeImg {
    display: grid;
    grid-template-columns: 1fr;
    }
    .largeImg img {
    max-width: 100%;
    display: none;
    }
    .largeImg img.active {
    display: block;
    animation: fadeIn 1s forwards ease;
    }
    .swapImg {
    display: block;
    margin: 25px auto;
    }
    @keyframes fadeIn {
    0% {
    opacity: 0;
    }
    100% {
    opacity: 1;
    transform: translateY(0);
    }
    }
    </style>
    
    
    </head>
    <body>
    <div class="gallery">
    <div class="largeImg">
    <img src="image_1.jpg" alt="" class="active">
    <img src="image_2.jpg" alt="">
    <img src="image_3.jpg" alt="">
    <img src="image_4.jpg" alt="">
    <img src="image_5.jpg" alt="">
    </div>
    <button class="swapImg">Swap Image</button>
    </div>
    
    <script>
    const images = document.querySelectorAll('.largeImg img');
    
    const swapImg = document.querySelector('.swapImg')
    
    let count = 0;
    swapImg.addEventListener('click', () => {
    count++;
    images.forEach((img) => {
    img.classList.remove('active')
    })
    
    if(count === images.length) {
    count = 0;
    }
    
    images[count].classList.add('active');
    })
    
    
    </script>
    
    </body>
    </html>

     

     

     

     

     

     

    AmySykes
    AmySykesAuthor
    Known Participant
    September 11, 2023

    Hi Osgood, Nice job. Very Well done. I like your solution and I appreciate all your help. Thank you!!

    Community Expert
    September 10, 2023

    Here is a basic of what I understood :

     

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Swap images</title>
    </head>
    <body>
        <button id="myButton">Swipe</button>
        <img id="myImg" src="" alt="Image">
        
        <script>
            // Here you create your array
            const images = [
                'a-one.jpg',
                'a-two.jpg',
                'a-three.jpg',
                // add all images that you want
            ];
            const bouton = document.getElementById('myButton');
            const image = document.getElementById('myImg');
            let index = 0; 
            // Instead of using a called function 
            // I used the new Javascript syntax
            bouton.addEventListener('click', () => {
                // you probably will have to adapt the image path 
                // I used the one that you use on the video
                image.src='img/' + images[index];
                index++;
                // If you want to restart, set the index to 0
                // once the array will be passed
                if (index >= images.length) {
                    index = 0;
                }
            });
        </script>
    </body>
    </html>
    
    AmySykes
    AmySykesAuthor
    Known Participant
    September 11, 2023

    Lena, You are a complete rock star!! Your solution is superb, easy to follow, and well thought out. Your coding is immaculate and very well commented which was super helpful. Thank you so much. I appreciate you.

     

    Community Expert
    September 11, 2023

    I'm glad it helped you! Thank you so much for your wonderful feedback!


    However, as reported in the exchange we had with @osgood_ , you may encounter a latency problem related to image loading.
    If you like, I can sketch out a snippet of a script that would allow preloading only from the next 1, or even 2, images.