• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

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

Participant ,
Sep 10, 2023 Sep 10, 2023

Copy link to clipboard

Copied

This demo's 3 column layout was created with Bootstrap. The hover button effect was created with CSS. See my video from yesterday to see the CSS and HTML coding I coded to obtain the hover button effect. This video was created so I could ask the Adobe Dreamweaver Community forum how can I use ...

Views

3.4K

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 6 Correct answers

Community Expert , Sep 10, 2023 Sep 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 th
...

Votes

Translate

Translate
LEGEND , Sep 10, 2023 Sep 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</titl
...

Votes

Translate

Translate
LEGEND , Sep 18, 2023 Sep 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');
}
})

Votes

Translate

Translate
Community Expert , Sep 19, 2023 Sep 19, 2023

Votes

Translate

Translate
Community Expert , Sep 19, 2023 Sep 19, 2023

All you have to do is google the subject, and you'll find tons of tutorials on the web. they're all pretty good, but it mostly depends on the entry level, the level covered, and the need to put it into practice at the same time, otherwise it remains mainly theoretical.

 

Regarding the basics, the link indicated by @BenPleysier can only be confirmed, MDN is a real source for beginners and experts alike, a must have!

 

As a complement, you can also start with :

...

Votes

Translate

Translate
LEGEND , Oct 02, 2023 Oct 02, 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) {

...

Votes

Translate

Translate
Community Expert ,
Sep 10, 2023 Sep 10, 2023

Copy link to clipboard

Copied

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>

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Participant ,
Sep 11, 2023 Sep 11, 2023

Copy link to clipboard

Copied

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.

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 11, 2023 Sep 11, 2023

Copy link to clipboard

Copied

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.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 11, 2023 Sep 11, 2023

Copy link to clipboard

Copied

To implement preloading, you can explore the following path :

 

On the one hand, you can isolate the preloading function on the basis of the current index :

function preloadNextImage() {
    // The use of modulo (%) allows us to loop easly on the number of images
    const nextIndex = (index + 1) % images.length;
    const nextImage = new Image();
    nextImage.src=images[nextIndex];
}

 

Then, on the other hand,

you first invoke this function when the page is loaded :

<script>
    // all the previous script
    preloadNextImage();
</script>

       

and then after the click :

bouton.addEventListener('click', () => {
    // all the previous script
    preloadNextImage();
});

    

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 11, 2023 Sep 11, 2023

Copy link to clipboard

Copied

@AmySykes , I've just seen that you've unpublished my reply as correct. Was there a problem?

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 11, 2023 Sep 11, 2023

Copy link to clipboard

Copied

@AmySykes , Once again, sorry, but you have just published my comment as correct, and not the initial reply 😉

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Sep 10, 2023 Sep 10, 2023

Copy link to clipboard

Copied

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>

 

 

 

 

 

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Participant ,
Sep 11, 2023 Sep 11, 2023

Copy link to clipboard

Copied

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

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 11, 2023 Sep 11, 2023

Copy link to clipboard

Copied

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.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Sep 11, 2023 Sep 11, 2023

Copy link to clipboard

Copied

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.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 11, 2023 Sep 11, 2023

Copy link to clipboard

Copied

Indeed, and this is the beauty of our daily business, any integration of elements in an interface can be continually improved in terms of ergonomics, contextualization according to peripherals and their screen qualities, taking into account accessibility, gestural interaction... and so on....

 

Your idea of using a transition between slides is one of them, and can be implemented either directly in HTML, or on the fly through elements created dynamicaly in the code, then it all depends on each person's wishes and approach.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Sep 11, 2023 Sep 11, 2023

Copy link to clipboard

Copied

quote

Your idea of using a transition between slides is one of them, and can be implemented either directly in HTML, or on the fly through elements created dynamicaly in the code, then it all depends on each person's wishes and approach.


By @L e n a

 

Using your original code example:

 

Include a function AFTER 'let index = 1;'

 

function fadeIn() {
image.classList.add('fadeIn');
setTimeout(function() {
image.classList.remove('fadeIn');
}, 700)
}
//Evoke function on page load
fadeIn();

 

Then call the function again when the button is clicked:

 

bouton.addEventListener('click', () => {
// Evoke function when button is clicked
fadeIn();

 

 

Add the css:

 

.fadeIn {
animation: fadeIn 700ms forwards ease;
}

@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}

 

 This will provide a basic fadeIn image effect which will soften the transition between images.

 

For a fade in/fade out effect that gets a bit more complex as you need to have 2 images on the page which morph into one another, that is not possible by just replacing the src link for another src link

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 11, 2023 Sep 11, 2023

Copy link to clipboard

Copied

Yes you’re right one need to add a second image and just few lines of code to yours.
To simplify, I posted the code on the studio demo’s page :
https://demo.puce-et-media.com/AmySykes/version-4.html

 

@AmySykes you should please remove validation from the last two comments that are validated as correct, and mark the first reply that contained the code. Or maybe a moderator could handle it, because it's confusing somehow.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Sep 11, 2023 Sep 11, 2023

Copy link to clipboard

Copied

quote

Yes you’re right one need to add a second image and just few lines of code to yours.
To simplify, I posted the code on the studio demo’s page :
https://demo.puce-et-media.com/AmySykes/version-4.html

 

By @L e n a

 

Yup, that's how it should be done, in my opinion, when swapping between images, always looks a lot more professional for just a little bit of extra thought and work.  

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Participant ,
Sep 12, 2023 Sep 12, 2023

Copy link to clipboard

Copied

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.

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Sep 12, 2023 Sep 12, 2023

Copy link to clipboard

Copied

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.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Participant ,
Sep 12, 2023 Sep 12, 2023

Copy link to clipboard

Copied

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. 

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Sep 13, 2023 Sep 13, 2023

Copy link to clipboard

Copied

Hi Amy,

 

Thanks. My preferred method is to use the array solution personally as suggested by Lena. I threw my solution into the ring as an option because some 'developers' are 'frightened' away when javascript goes up a level, so it's a good alternative, particularly if not many images are being processed. There's many ways to achieve practically the same results these days...........maybe l will throw a react js option into the mix........on second thoughts, enough is enough.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 12, 2023 Sep 12, 2023

Copy link to clipboard

Copied

@osgood_ , you're preaching to the choir, the question isn't about that but about not marking comments as good answers when they are just comments.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Sep 12, 2023 Sep 12, 2023

Copy link to clipboard

Copied

quote

@osgood_ , you're preaching to the choir, the question isn't about that but about not marking comments as good answers when they are just comments.


By @L e n a

 

Does that really matter that much....I mean the DW forum is hardly a place that attracts so much traffic that its going to be a huge concern? I'm sure anyone that runs across this thread can work it for themselves, if not, then they are probably already dead.........I would assume.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 12, 2023 Sep 12, 2023

Copy link to clipboard

Copied

quote

Dear Adobe Lena's,

By @AmySykes

Once again, thank you for your kind words. I'd like to make it clear that I'm not an Adobe employee; this forum is largely made up of only passionate users 😉

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Participant ,
Sep 18, 2023 Sep 18, 2023

Copy link to clipboard

Copied

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;
}
@keyframes 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>

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Sep 18, 2023 Sep 18, 2023

Copy link to clipboard

Copied

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');
}
})

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Participant ,
Sep 18, 2023 Sep 18, 2023

Copy link to clipboard

Copied

It WORKS!!! Thank you so much.♥♥♥

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines