Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 31, 2022 09:52 pm GMT

A JavaScript Slider in 8 Lines

In this post well 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 well build:

Image description

Lets 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.


Original Link: https://dev.to/wolffe/a-javascript-slider-in-8-lines-42bh

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To