A JavaScript Slider in 8 Lines
source link: https://dev.to/wolffe/a-javascript-slider-in-8-lines-42bh
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
A JavaScript Slider in 8 Lines
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>
Enter fullscreen mode
Exit fullscreen mode
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;
}
Enter fullscreen mode
Exit fullscreen mode
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
Enter fullscreen mode
Exit fullscreen mode
Check out the JavaScript code for a full breakdown and a slider demo.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK