What are some solutions for ensuring that the dots on a slideshow function automatically?

My attempt to showcase an automated slideshow seems to be partially successful. The images are changing as intended, but the dots below aren't functioning properly. Although clicking on a dot triggers the desired action, I am aiming for all dots to turn white simultaneously with each slide transition.

Below is the HTML file snippet:

<div class="slideshow-container">
            <div class="mySlides fade">
                <img src="images/laptop.png" class="welcome__img" style="width:100%">
            </div>
            <div class="mySlides fade">
                <img src="images/laptop.png" class="welcome__img" style="width:100%">
            </div>
            <div class="mySlides fade">
                <img src="images/laptop.png" class="welcome__img" style="width:100%">
            </div>
            <div style="text-align:center">
                <span class="dot" onclick="currentSlide(1)"></span>
                <span class="dot" onclick="currentSlide(2)"></span>
                <span class="dot" onclick="currentSlide(3)"></span>
            </div>
        </div>

Here is the CSS code:

.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

/* Hide the images by default */
.mySlides {
    display: none;
}

.dot {
  cursor: pointer;
  height: 10px;
  width: 10px;
  margin: 0 2px;
  background-color: $grey;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active, .dot:hover {
  background-color: $white;
}

/* Fading animation */
.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {opacity: .4} 
  to {opacity: 1}
}

@keyframes fade {
  from {opacity: .4} 
  to {opacity: 1}
}

The JavaScript segment:

var slideIndex = 0;
showSlides();

function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    var dots = document.getElementsByClassName("dot");
    for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none"; 
    }
    slideIndex++;
    if (slideIndex > slides.length) {slideIndex = 1} 
    slides[slideIndex-1].style.display = "block"; 


   for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
    setTimeout(showSlides, 2000); // Change image every 2 seconds
}

While the setTimeout function operates correctly, the issue persists with the dots failing to change their fill color.

Answer №1

Make sure to include this code snippet inside your for-loop within the showSlides function.

if (i === slideIndex) {
  dots[i].className = "dot active";
} else {
  dots[i].className = "dot";
}

Answer №2

If you want to switch the active class for each slide show, you can iterate through the dots:

var dotActive = document.querySelector('.dot.active');
if (dotActive == null) { // if no dot is active...
    document.querySelector('.dot').classList.add("active");
} else { // remove the current active class and set it to the next element
    dotActive.classList.remove("active");
    (dotActive.nextElementSibling || document.querySelector('.dot')).classList.add("active");
}

Instead of using parameters like 1, 2, or 3, you can utilize this and event.

var slideIndex = 0;

showSlides();

function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    var dots = document.getElementsByClassName("dot");
    for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
    }
    slideIndex++;
    if (slideIndex > slides.length) {slideIndex = 1}
    slides[slideIndex-1].style.display = "block";

    var dotActive = document.querySelector('.dot.active');
    if (dotActive == null) {
        document.querySelector('.dot').classList.add("active");
    } else {
        dotActive.classList.remove("active");
        (dotActive.nextElementSibling || document.querySelector('.dot')).classList.add("active");
    }
    setTimeout(showSlides, 2000); // Change image every 2 seconds
}
/* Hide the images by default */
.mySlides {
    display: none;
}
.dot {
    cursor: pointer;
    height: 10px;
    width: 10px;
    margin: 0 2px;
    background-color: grey;
    border-radius: 50%;
    display: inline-block;
    transition: background-color 0.6s ease;
}

.active, .dot:hover {
    background-color: white;
}

/* Fading animation */
.fade {
    -webkit-animation-name: fade;
    -webkit-animation-duration: 1.5s;
    animation-name: fade;
    animation-duration: 1.5s;
}

@-webkit-keyframes fade {
    from {opacity: .4}
    to {opacity: 1}
}

@keyframes fade {
    from {opacity: .4}
    to {opacity: 1}
}
<div class="slideshow-container">
    <div class="mySlides fade">
        <img src="https://dummyimage.com/100x100/000/fff&text=1" class="welcome__img" style="width:100%">
    </div>
    <div class="mySlides fade">
        <img src="https://dummyimage.com/100x100/000/fff&text=2" class="welcome__img" style="width:100%">
    </div>
    <div class="mySlides fade">
        <img src="https://dummyimage.com/100x100/000/fff&text=3" class="welcome__img" style="width:100%">
    </div>
    <div style="text-align:center">
        <span class="dot" onclick="currentSlide(1)"></span>
        <span class="dot" onclick="currentSlide(2)"></span>
        <span class="dot" onclick="currentSlide(3)"></span>
    </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can someone guide me on the proper implementation of the 'useEffect' hook in React version 18?

I'm currently working on a project following a YouTube tutorial that uses React 17, while I'm using React 18. Everything has been going smoothly so far, but I've hit a roadblock with formatting animated text. The specific task I'm stuck ...

Definition of Stencil Component Method

I'm encountering an issue while developing a stencil.js web component. The error I'm facing is: (index):28 Uncaught TypeError: comp.hideDataPanel is not a function at HTMLDocument. ((index):28) My goal is to integrate my stencil component i ...

The process of binding two variables in the same select element

Here is the code snippet that I am working with: <div class="form-group "> <label for="field_type"><b>Type</b></label> <div class="input-icon right"> <select required class="form-control" ...

When I resize the screen size, my multiple item carousel in Bootstrap is failing to adjust and collapses

Whenever I try to resize the output screen, the carousel collapses and the last few items disappear. I really need the carousel to stay intact even when resizing. Can someone please assist me with this issue? Link to my CodePen ResCarouselSize(); $(w ...

What is the best way to remove the class "active" from only one of the <li> elements using jQuery?

I am currently facing a challenge in figuring out how to remove the "active" class from just one of my lists. Here is an example of my navigation bar: <div class="container"> <ul class="nav"> <li class="active"><a href="#">& ...

Adding numerical values to circles can be achieved by implementing various methods,

I've been utilizing jsFiddle to generate multiple circles at specific locations. How can I include numbers within these circles so that each one is labeled with a number? Check out the jsfiddle code here function draw_circle(center_x, center_y){ ...

Retrieve all node names from a .dae file using three.js

When I import a collada file into my scene, I am trying to figure out how to list all the node names. Can anyone help me with this? Here is what I have tried so far, but it only gives me one name: var dae; loader.options.convertUpAxis = true; loader.load ...

Change the CSS dynamically

I'm curious about how to create a similar effect like the one on this page: On the left side, there is a panel that allows for adjusting the template. What I've noticed is that when I change the color, different CSS files are used (blue.css, pur ...

Steps to transfer a JavaScript variable to a PHP session

Currently, I am in the process of retrieving the value of a checkbox and assigning it to a PHP session variable. Below is the relevant portion of the code: The checkbox: $html .= '<span><input type="checkbox" id="checkbox' ...

adjust the value of an attribute in a dynamic stylesheet using jquery

I'm trying to create a dynamic stylesheet using a combination of jquery, css, php, and html. My approach involves making an ajax request (using jquery) to pass the width of my screen to a php css file. However, I am facing an issue where the php css f ...

What is the reason behind Ember choosing to install everything as devDependencies rather than regular dependencies?

Ember CLI applications have a package.json file that lists everything as dev dependencies, including packages needed in the app's production version such as ember and ember-data. If you would like to see an example, check out this sample: https://git ...

I'm trying to figure out the best way to successfully pass a prop to another component in TypeScript without running into the frustrating issue of not being able to

I have been facing an issue while trying to pass a prop from a custom object I have defined. The structure of the object is as follows: export type CustomObjectType = { data?: DataObject }; export type DataObject = { id: number; name: stri ...

Error: The function callback.apply is not a valid function (Node.js and Mongodb)

Encountered an error when adding the line "{ upsert: true }": Error message: TypeError: callback.apply is not a function // Accessing routes that end in /users/competitorAnalysisTextData // ---------------------------------------------------- router . ...

If the overflow-x property is set to hidden for the html and body elements, the links in the footer will become unclickable as they will

Situation: Consider the following scenario with a simplified HTML example: position the footer behind the content and make it stick to the bottom when reaching the end of the page, the footer should slide up from behind the content I achieved this layo ...

Adding the highcharts-more.src.js file to an Angular 2 project: A step-by-step guide

I have linked highcharts-more to the system variable: 'highcharts-more': 'node_modules/highcharts/highcharts-more.src.js' But I keep getting an error message saying: Error in dev/process/templates/detail.template.html:40:33 ORIGINAL ...

Encountering an issue with React and Google charts: Unable to read property 'push' of undefined

I encountered a strange issue with React and my Google Charts. Initially, when I log in to the page displaying my chart, everything appears as expected. However, when I import new data to update the values on the chart, it suddenly disappears, and I am pre ...

Is it possible for comments in HTML and CSS to cause issues with rendering?

Could HTML or CSS comments potentially lead to rendering issues? HTML Comment Example: <!-- additional details --> CSS Example: /* more information */ ...

The designation is being acknowledged as a <div>

I am facing an issue with a div structure that contains a label and 4 child divs. My goal is to apply CSS and jQuery effects to only the child divs, excluding the label. To achieve this, I implemented the following code: HTML: <div class="score row-fl ...

Having trouble installing Moment and Material Moment Adapter in Angular?

To customize the date format in datepicker controls, I need to have both Material and Material-Moment-Adapter installed. Here is how I installed moment: npm install moment --save And for Material-Moment-Adapter: npm i @angular/material-moment-adapter How ...

The ASP.Net email contains a hyperlink designed to open in a new window

I am currently facing an issue with an email I need to send. The problem lies in the hyperlink that is intended to open a specific page in a new tab or window upon clicking. The main issue at hand is that there is no space between the querystring variable ...