Is there a way to seamlessly transition between images in a slider every 3 seconds using javascript?

<!DOCTYPE html>

<html>

<head>

<title>Hello</title>

<meta http-equiv="Content-Type" type="text/html" charset="UTF-8"/>

<style>

*{margin:0; padding:0;}

.mySlides{
          position:relative;
  width:1000px;
  margin:40px auto;
  display:table;
 }
 
.number{
        position:absolute;
margin:20px;
   }
   
.text{
      position:absolute;
  bottom:20px;
  text-align:center;
  width:100%;
 }
 
.prev, .next{
             position:absolute;
 top:40%;
 background-color:black;
 color:white;
 padding:20px;
 cursor:pointer;
 user-select:none;
        }

.next{
      right:0;
 }

.text-align{
            text-align:center;
   }
 
.dot{
     width:30px;
 height:30px;
 background-color:gray;
 display:inline-block;
}

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

</style>

</head>

<body>

<div class="mySlides">
<div class="number">1/4</div>
<img src="images/slide1.jpg" width="100%"/>
<div class="text">Text 1</div>
</div>

<div class="mySlides">
<div class="number">2/4</div>
<img src="images/slide2.jpg" width="100%"/>
<div class="text">Text 2</div>
</div>

<div class="mySlides">
<div class="number">3/4</div>
<img src="images/slide3.jpg" width="100%"/>
<div class="text">Text 3</div>
</div>

<div class="mySlides">
<div class="number">4/4</div>
<img src="images/slide4.jpg" width="100%"/>
<div class="text">Text 4</div>
</div>

<a class="prev" onclick="plusSlides(-1)">&#10094;</a>

<a class="next" onclick="plusSlides(1)">&#10095;</a>

<div class="text-align">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
<span class="dot" onclick="currentSlide(4)"></span>
</div>

<script>
var slideIndex=1;
showSlides(slideIndex);

function plusSlides(n){

showSlides(slideIndex+=n);

}

function currentSlide(n){

showSlides(slideIndex=n);

}

function showSlides(n){

var i;

var slides=document.getElementsByClassName("mySlides");

var dots=document.getElementsByClassName("dot");

if(n>slides.length){slideIndex=1;}

if(n<1){slideIndex=slides.length;}

for(i=0; i<slides.length; i++){

slides[i].style.display="none";

}

for(i=0; i<dots.length; i++){

dots[i].className=dots[i].className.replace("active", "");

}

slides[slideIndex-1].style.display="block";

dots[slideIndex-1].className+=" active";

}
</script>

</body>

</html>

Is there a way to change the image/slider every 3 seconds using JavaScript?

I've tried using setTimeout(showSlides, 3000); but what additional code do I need to add?

When I use slideIndex++; and setTimeout(showSlides, 3000); the slider changes every 3 seconds, but the slider buttons don't match with the images. Any suggestions on how to sync the slider buttons with the images?

Answer №1

For a more polished look, consider using Owl Carousel

In the realm of commercial development, self-coded sliders are often overlooked.

If you're curious about how it would work, check out this working example

I've added 4 lines below:

var timer = setInterval(function(){
    slideIndex++;
    showSlides(slideIndex);
},3000);

It seems to be functioning well without any issues

Does this align with what you were looking for?

Answer №2

While reorganizing your code may be beneficial, the current addition that I suggest is:

setInterval(function(){ plusSlides(1); }, 3 * 1000)

Answer №3

Give this a shot:

<!DOCTYPE html>
<html>
<head>
<style>
.mySlides {display:none;}
</style>
</head>
<body>
<div style="max-width:500px">
<div class="mySlides">
  <img  src="example.com/snake1.png" style="width:100%">
  <p>Snake 1</p>
<p>1/4</p>
    </div>
    <div class="mySlides">
  <img  src="example.com/snake2.png" style="width:100%">
  <p>Snake 2</p>
<p>2/4</p>
    </div>
    <div class="mySlides">
  <img  src="example.com/snake3.png" style="width:100%">
  <p>Snake 3</p>
<p>3/4</p>
    </div>
    <div class="mySlides">
  <img  src="example.com/snake4.png" style="width:100%">
  <p>Snake 4</p>
<p>4/4</p>
    </div>

</div>

<script>
var myIndex = 0;
carousel();

function carousel() {
    var i;
    var x = document.getElementsByClassName("mySlides");
    for (i = 0; i < x.length; i++) {
       x[i].style.display = "none";  
    }
    myIndex++;
    if (myIndex > x.length) {myIndex = 1}    
    x[myIndex-1].style.display = "block";  
    setTimeout(carousel, 3000); // Change image every 3 seconds
}
</script>
</body>
</html>

Not sure about the dots, though...

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

Are there any compatibility issues with uuid v1 and web browsers?

After researching, I discovered that uuid version1 is created using a combination of timestamp and MAC address. Will there be any issues with browser compatibility? For instance, certain browsers may not have access to the MAC address. In my current javaS ...

Dropped down list failing to display JSON data

I created a website where users can easily update their wifi passwords. The important information is stored in the file data/data.json, which includes details like room number, AP name, and password. [ {"Room": "room 1", "AP nam ...

What is causing the section to cover the navbar?

My content is overlapping the navbar on certain screen sizes, and I'm not sure why. Any ideas on how to fix this issue? Would wrapping everything in a container help? Currently using bootstrap v5.3.0-alpha1. Additionally, when I have a collapsed nav ...

Is there a quicker alternative to html.fromhtml for adding html-styled text to textviews?

Looking for a quicker solution than using Html.fromHtml to set text in multiple TextViews. Open to suggestions of support libraries that may offer a faster method. Spannables have been considered, but they don't allow for line breaks without using Spa ...

Failure to append an object to the array occurs when submitting an HTML form

I am facing an issue with a form that is supposed to add input values to an array as objects when submitted. However, every time I submit the form, the console briefly shows that there is an array with one object, only for it to disappear. Below is the f ...

Exploring the World with AngularJS and Google Maps API through ngGeolocation

Having some difficulty displaying my geolocation on Google Maps API using a marker. I am utilizing the ng controller ngGeolocation and the http://angular-ui.github.io/angular-google-maps/ Previously, I hardcoded the marker and map location without any is ...

Issue with Navbar Collapse Toggle not deactivating (following transition from bootstrap v4 beta to v4 alpha 6)

Recently, I encountered an issue with my navbar after switching to v4 alpha 6 in order to utilize the responsive utilities that this version offered. If you visit the following page: , you will see what I mean. Prior to upgrading to v4 alpha 6, all menu ...

Webpack-dev-middleware is serving the bundle on a port that is distinct from the application

Recently, I've been developing a React boilerplate that fully utilizes Apollo-Client and GraphQL. The setup of my application consists of one node process overseeing an Express server on port 3000 to render the app, and another Express server on port ...

Adjust the size of the HTML input font to decrease as additional text is entered

Is it possible to create an HTML text field that automatically adjusts the font size when the user types more characters than it can display? I know Acrobat has this feature for forms, but I'm looking to implement it in HTML. So, imagine having a te ...

Activate a click on a div element to enable smooth scrolling when using the page down and page up keys

Whenever I directly click on my div, the pageUp and pageDown keys scroll the contents of the div. But when I trigger a click programmatically, the scrolling with pageUp and pageDown stops working. How can I enable scrolling with pageUp and pageDown without ...

Automatically generated list items are failing to react to the active class

I am facing an issue with two divs in my project. The first div uses the Bootstrap class list-group and is populated with a basic example provided by Bootstrap. The second div is supposed to be populated with list-group-items obtained from an AJAX GET requ ...

What is the best way to add methods to underscore without making them available globally?

Have you added multiple methods to underscore within your package? _.mixin({ foo: function() {}, bar: function() {} //etc }); If you're concerned about potential conflicts with the main application or other packages, what's the best way ...

When using NextJS, the dynamically generated HTML elements do not get affected by CSS repaint

Recently, I encountered an issue while working on a Next.js project involving the addition of an external script that uses vanilla JavaScript to dynamically create nodes. Despite importing global CSS at the top of my _app.js file, I noticed that the styles ...

Creating a unique custom icon by leveraging the material UI icons - a step-by-step guide

I am looking to create an arrow graphic similar to the one shown in the image below https://i.stack.imgur.com/k9TvH.png Originally, I was able to achieve this using SVG - <svg height='24' width='12' style={{ marginBottom: '-4p ...

What is the best way to link HTML transformations across several classes?

Is it possible to combine multiple transforms in a single element to create a unique end result? It seems that when applying multiple transform properties to an element, only one of them will be recognized. For example, trying to transform a div with bot ...

Is it possible to use jQuery to identify when an item is located on a new line within a textarea?

I am looking to create an array from the content within a textarea. The textarea holds a varying list of names, each consisting of only one word without any spaces. Currently, I have the following code in place. However, my issue lies in the fact that the ...

React: Transforming mongoDB date format into a more user-friendly date display

An entry saved in MongoDB contains a property called "createdAt" with a timestamp. Take a look at the example below: createdAt: 2021-10-26T12:24:33.433+00:00 If we consider this date to be today, how can I achieve the following outcomes?: Show this date ...

What are the best practices for utilizing AngularJS's $sanitize service?

Recently, I stumbled upon a tutorial discussing authentication in AngularJS. The tutorial showcased an AuthenticationService that was structured similarly to this: angular.module("auth").factory("AuthenticationService", function ($http, $sanitize) { ...

How can I retrieve the second letter in Materialize CSS FormSelect by using the keyboard?

On my website that utilizes materializeCSS and Jquery, I have encountered an issue with a select box containing numerous options. Typically, when using a select box, I can press a letter multiple times to cycle through options starting with that letter. ...

JS implementing a listener to modify a Google Map from a separate class

Currently, I am in the process of migrating my Google Map functionality from ionic-native to JavaScript. I am facing an issue while attempting to modify the click listener of my map from a separate class. The problem seems to be related to property errors. ...