Tips for adjusting the time interval on an automatic slideshow when manual controls are in play

I'm having trouble with my slideshow. I want it to run automatically and also have manual controls, but there are some issues. When I try to manually control the slides, it takes me to the wrong slide and messes up the timing for the next few slides. Does anyone have a solution?

I've attempted changing the slideIndex to 0, but that just takes me back to the first slide instead of advancing to the next one.

  
    var slideIndex = 0;
    showSlides(slideIndex);

    function plusSlides(n) {
      showSlides(slideIndex += n);
    }

    function currentSlide(n) {
      showSlides(slideIndex = n);
    }

    // rest of the JavaScript code...

   
     * {box-sizing: border-box;}
      // CSS styles...

  
    
    < h2>Automatic Slideshow</h2>
    < p>Change image every 10 seconds:</p>

    // HTML markup...
  

The expected interval is 10 seconds, but it's only a couple of seconds. The next/previous slide buttons aren't functioning as expected either.

Answer №1

It seems the issue lies in how timeouts are set for your slideshow buttons. Pressing next or previous doesn't cancel old timeouts, causing multiple slides to transition simultaneously within the desired time frame.

To resolve this, consider using intervals instead of individual timeouts and managing them outside functions.

Upon user input (forward/back), clear the current interval and create a new one to prevent overlapping transitions and ensure smooth carousel movement.

JAVASCRIPT

let slideIndex = 0;
const slideTime = 5000;
let slideInterval = setInterval(() => changeSlide(true), slideTime);

function jumpSlide(forward) {
  clearInterval(slideInterval);
  changeSlide(forward)
  slideInterval = setInterval(() => changeSlide(true), slideTime);
}

function changeSlide(forward) {
  const slides = document.getElementsByClassName('slide');
  slides[slideIndex].classList.remove('active');
  if (forward) {
   if (slideIndex + 1 > slides.length - 1) {
    slides[0].classList.add('active');
    slideIndex = 0;
  } else {
    slides[slideIndex + 1].classList.add('active');
    slideIndex ++;
  } 
  } else {
    if (slideIndex - 1 < 0) {
    slides[slides.length - 1].classList.add('active');
    slideIndex = slides.length - 1;
  } else {
    slides[slideIndex - 1].classList.add('active');
    slideIndex --;
  }
  }
}

HTML

<div class='slide-container'>
<div class='slide active'></div>
<div class='slide'></div>
<div class='slide'></div>
</div>
<button onclick='jumpSlide(false)'>last slide</button>
<button onclick='jumpSlide(true)'>next slide</button>

CSS

.slide-container{
  display: flex;
}
.slide {
  width: 50px;
  height: 50px;
  background-color: rgba(0, 0, 0, 0.25)
}
.active {
  background-color: red;
}

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 anyone tell me why my index.html file isn't recognizing the style.css file located in my css directory

In the directory structure below, I have the following files: mywebsite/ ├── css/ │ ├── style.css │ ├── index.html This is my HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8 ...

Deliver a response to recipients through the "button" feature within the WhatsApp cloud API

I'm working on building a chatbot for my booking company. Here is an outline of my initial bot flow: const axios = require("axios").default; function initialize_bot(message, phone_number, access_token, sender, username) { if (message === ...

Issues verifying the selected value for the ajax request

One of the challenges I'm facing is related to a form that requires specific user selections. If the user chooses a value of 1, the form can be submitted without any additional steps. However, if they select values 2 or 3, they must then choose an opt ...

How to retrieve email input using SweetAlert2 in PHP?

Hello there! I'm curious about the most effective method for integrating PHP with Javascript. My goal is to execute some coding tasks once an email address has been entered. swal({ type: "success", title: "Congrats!", text: "Please enter your P ...

Tips for retrieving the value of a corresponding data attribute by the text within a div using jQuery in JavaScript

I have several divs with different names and values assigned to the data attribute data-category Now, I am in need of retrieving the value of data-category based on specific text present inside the div. <div class='ext-category' data-categor ...

Using backslashes to escape JSON values within a value in Angular

When retrieving JSON data from the backend, I often encounter an issue where the value is set to "key": "\$hello" and it results in an "Unexpected token d". Is there a way in Angular to handle or escape these characters once received from the server? ...

Tips for setting the id parameter on the asp-route-id for the modal button

My code is causing me some trouble. I have a table with 3 columns: category, subcategories and actions. In the third column, I display buttons "Edit" and "Delete". Here is a snippet of my code: <tbody> @foreach (var category in Model.ToList() ...

Utilizing jQuery to seamlessly animate decimal values

Currently facing a challenge while trying to animate a number from 0 to 36.6. The issue is that the end value gets rounded up to 37 instead of displaying as 36.6, which you can observe in this fiddle: http://jsfiddle.net/neal_fletcher/0f3hxej8/ Required ...

Having trouble loading environment variables in NextJS on Heroku?

I am currently utilizing NextJS and deploying my application on Heroku. When the page initially loads, I am able to retrieve data through getInitialProps without any issues. However, when trying to access this data in a regular function, I encounter an er ...

Tips for eliminating the backslash introduced by JQuery

Switching back from framework 4.5 to 4.0 caused several issues that needed fixing. One significant change I noticed was that jQuery started escaping double quotes. Is there a way to stop this behavior? I attempted datatest = datatest.replace("\\ ...

I currently have two responsive menus and I'm trying to figure out how to modify the javascript so that when one menu is opened, the other

I am facing an issue with my responsive menus on a webpage, similar to the example provided in the jsfiddle link below. Currently, when one menu is open and I click on another, both remain open. How can I modify the JavaScript code so that when one menu op ...

What is the best way to determine if my code is executing within a NodeJS environment?

I am working on a piece of JavaScript code that is specifically meant to run in NodeJS. It uses functions like require(), so running it elsewhere would cause errors. I want to add a runtime check to ensure the code is only executed within NodeJS and displa ...

Using regular expressions in Sublime Text 2 to replace text in JSON files can greatly improve your workflow

After using an online web tool to convert an Excel file to JSON, I now require assistance in replacing certain values within the JSON. Currently, I am using Sublime Text 2. {"Time (GMT-04:00)":"2010-07-06 08:30:00","Skin temp - average":"34,2043","Step Co ...

Is there a way to transform an HTML table into an Excel file with several sheets?

Is there a way to transform multiple HTML tables into an Excel file with multiple worksheets? I need assistance with this task. You can find an example here function exportTablesToExcel() { var tableContent = "<table border='2px'>< ...

Determining when a function is triggered from the JavaScript console

Is there a way to conceal a function in JavaScript console so that it's inaccessible for calling? Let me give you some context - let's say I have a JavaScript function that adds records to a database using Ajax. The issue is, anyone can call thi ...

import an external JavaScript file into another JavaScript file

Is there a way to include an external JavaScript file into tinyMCE and access all its functions? For example - I want to integrate jQuery Mobile with tinyMCE and make all its functions available. This problem arose while attempting to incorporate the jQ ...

Guide on exporting a reducer from a Node module built on React Redux

I am currently working on a project that requires importing a component from an external node module. Both the project and the component utilize React and Redux, and I intend for them to share the same store. Below is a snippet of the reducer code for the ...

Is it possible for a CSS Transition/Transform to ease out smoothly yet not ease in at all?

It appears that the transition is smoother when I stop hovering over the button, compared to when I actually hover. Why might this be? .button_1 { border-width: 0.8px; border-color: Lightgray; background-color: hsla(209, 72%, 59%, 0.85); ...

Lunar - incorporate route parameter into DOM query_operation

Is there a way to take a route parameter and use it to trigger a click event on a DOM element? The issue is that onBeforeAction is called before the DOM is fully loaded. Any suggestions on how to solve this problem? JS onBeforeAction: function(){ var ...

How to create a listview with stylish rounded corners in jQuery mobile using CSS?

I'm attempting to customize the appearance of a jQuery mobile listview using CSS by adding a border radius to each item. Although things seem to be working mostly as expected, I've encountered a problem where only the first and last <li>&l ...