A simple slider(carousel) in JavaScript

A simple slider(carousel) in JavaScript

Sliders are a common feature for websites. many developers have implemented this solution using some common JavaScript libraries, today I will take you through the process of building your own custom slider, that is very simple to use and customize, with just plain JavaScript.

We will call our slider “vita-slider”, so quickly create a new folder and open it using using your favorite editor. In the new folder you created, create an additional folder for our slider images, and also in the root directory create the index.html, style.css and script.js files.

In the index.html file, inside the head element, we will reference our style.css and script.js files as shown as shown in the following code snippet

<html lang=”en-US”>
 <head>
  <title>Vita Slider</title>
  <link rel=”stylesheet” href=”style.css” />
  <script type=”text/javascript” src=”script.js”></script>
 </head>
 …
</html>

Our JavaScript file is now referenced in your HTML web page, Hence We can now can write JavaScript codes in this file that will run on our web page.

#Create Figure Elements For Carousel

Within the body element, we add a new section element after the header element add as this

<html lang=”en-US”>

    <head>
        <title>Simple Slider</title>
        <link rel=”stylesheet” href=”style.css” />
        <script type=”text/javascript” src=”script.js”></script>
    </head>

    <body>
        <header>
            …
        </header>
        <section>
        </section>

    </body>

</html>

Within the section element, we add a new figure tag, and inside this figure tag, goes our image tag.

Update the new img tag by setting the src attribute to the value images/picurename.png and also  setting the alt attribute to any value.

Within the new figure tag, we add a new figcaption element and update it by setting the content to any caption of your choice.

After doing this our index.html page will look like this :

<!DOCTYPE html>
<html lang=”en”>

<head>
    <meta charset=”UTF-8">
    <meta name=”viewport” content=”width=device-width, initial-scale=1.0">
    <meta http-equiv=”X-UA-Compatible” content=”ie=edge”>
    <link rel=”stylesheet” href=”style.css”>
    <script src=”script.js”></script>
    <title>Document</title>
</head>

<body>
    <section id=”carousel”>
        <figure class=”visible”>
            <img src=”images/car.png” alt=”Efficient Cars”>
            <figcaption>2020, scientists promised us electric cars </figcaption>
        </figure>
        <figure class=”hidden”>
            <img src=”images/health.png” alt=” Health is wealth”>
            <figcaption>Health iswealth</figcaption>
        </figure>
        <figure class=”hidden”>
            <img src=”images/nature.png” alt=” Nature”>
            <figcaption> Hurricane Threatens to Touch Down on the East Coast This Weekend</figcaption>
        </figure>
    </section>
    Lorem ipsum, dolor sit amet consectetur adipisicing elit.
    Ipsa distinctio alias, nobis numquam repudiandae possimus
    nam aliquid vel rerum soluta quam! Esse molestias hic neque
    incidunt recusandae fuga, omnis laborum?
</body>

</html>

#Writing Our CSS

We apply Carousel CSS Styles to target the img elements that are direct descendants of figure elements that are direct descendants of the section element with an id of carousel. This rule set should include the following declarations, and the goal is to hide the figure elements by default.

section#carousel > figure > img {
display: none;
margin: 0px auto;
}

We also add CSS rule set that targets the img elements that are direct descendants of figure elements referencing the visible class that are direct descendants of the section element with an id of carousel. This rule set should include the following declarations, and will reference the class visible

section#carousel > figure.visible > img {
 display: block;
 position: relative;
 overflow: hidden;
}

Add a CSS rule set that targets the figcaption elements that are direct descendants of figure elements that are direct descendants of the section element with an id of carousel. This rule set should include the following declarations
This rule will hide the figcaption elements by default.

section#carousel > figure > figcaption {
 display: none;
}

Add a CSS rule set that targets the figcaption elements that are direct descendants of figure elements referencing the visible class that are direct descendants of the section element with an id of carousel. This rule set should include the following declarations:
This rule will show only the figcaption elements that reference the class visible.

section#carousel > figure.visible > figcaption {
 display: block;
 text-align: center;
 font-weight: bold;
 font-size: 1.5em;
}

Our complete style.css should look like this:

body {
    font-family: Itim;
    color: aqua;
    text-align: center;
}

section#carousel>figure>img {
    display: none;
    margin: 0px;
}

section#carousel>figure.visible>img {
    display: block;
    overflow: hidden;
    position: relative;
    margin: 0px auto;
}

section#carousel>figure>figcaption {
    display: none;
}

section#carousel>figure.visible>figcaption {
    display: block;
    text-align: center;
    font-weight: bold;
    font-size: 1.5em;
}

#Implementation of Carousel using JavaScript

We will create a new variable called slideInterval with the initial value set to 3500.
Then we will Create a new function named getFigures. This function
retrieve all of the figure elements within a section element using the ID carousel. It will return the resulting array of the selected elements

Similarly, we will also create another function named moveForward. This function iterates over the figure elements in the section element.

It removes the visible class from the current figure element, then adds the class to the next figure element. Once complete, it uses the setTimeout function to invoke itself again after a specified amount of time .

The last function, startPlacback is used to set the program in motion in a forever loop

In summary the JavaScript logic simply adds the visible CSS class to the next image in the rotation approximately every 4 seconds, and adds the hidden CSS class to others.

let slideInterval = 4000;

function getFigures() {
    return document.getElementById('carousel').getElementsByTagName('figure');
}

function moveForward() {
    var pointer;
    var figures = getFigures();
    for (var i = 0; i < figures.length; i++) {
        if (figures[i].className == 'visible') {
            figures[i].className = '';
            pointer = i;
        }
    }

    if (++pointer == figures.length) {
        pointer = 0;

    }
    
    figures[pointer].className = 'visible';
    setTimeout(moveForward, slideInterval);

}

function startPlayback() {
    setTimeout(moveForward, slideInterval);
}

startPlayback();

Yes, we have finally implemented a simple carousel using JavaScript, and I believe this tutorial helps you.

Don’t forget to like and share this tutorial with your friends, drop your comments on the comment section and follow my on twitter for more amazing tutorials.

Download and star the full version of this code from my GitHub repository

Join the discussion

5 comments

Vivvaas’ Corner

Learn skills that matters from a community of talented developers and writers whose joy is to write in a way that you will understand.