In this post we’ll build a minimal JavaScript slider, with no dependencies. The smallest, actually, without the actual slides’ HTML content: 8 lines of JavaScript.
Building a slider or a text rotator shouldn't use an insane amount of JavaScript and it should leverage modern CSS as much as possible.
The trick in this tutorial is matching CSS animation timing with the JavaScript setInterval()
value.
This is what we’ll build:
Let’s start with the HTML code, which, in this case, is one <div>
element:
<div id="slider--text"></div>
We will populate this element later using JavaScript.
Styling is optional, but, for the sake of this tutorial, I styled the slider to center align the content, both vertically and horizontally. I have also used a basic animation where I added opacity and a transform property.
.fade-in {
animation: fade 4s infinite;
}
Note how my 4 second animation will match the 4000 milliseconds in the code below.
Next, we add the JavaScript "sliding" functionality by checking if the element exist, and, if it does, we create an array of strings to slide. Note that you can use HTML.
Next, we create the slider by looping through the slides, and replacing the HTML inside the #slider--text
element with the slide content. That is all!
Next, we call the slider so that it runs immediately, and then we call it every 4 seconds using a setInterval()
function.
The gist of the JavaScript code is below:
const slider = () => {
document.getElementById("slider--text").innerHTML = slides[i];
document.getElementById("slider--text").classList.add('fade-in');
(i < slides.length - 1) ? i++ : i = 0;
};
setInterval(slider, 4000); // Slide every 4 seconds
Check out the JavaScript code for a full breakdown and a slider demo.
Top comments (0)