Carousel Slider

Written by @phuang 2 October 2022

Sometimes it's necessary to show a sequence of images or "slides" to group content on your website without taking up too much space. Below is the code for a simple carousel slider. 1. Add the css in an external referenced .css file or in the header tag. 2. Add the javascript code in an external referenced .js file and reference it at the end of the body tag. 3. Add the html markup file to wherever you want your carousel gallery to be. 4. Modify the settings portion of the javascript file to add additional slide by adding more image sources. 5. Feel free to modify the carousel item css to fit your own needs. Enjoy.

Code Snippet:

                                                
                                                <!-- this script is provided by https://www.javascriptfreecode.com coded by: Kerixa Inc. -->


<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Carousel Tutorial</title>

<!-- font awesome library include 4.7 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" integrity="sha512-5A8nwdMOWrSz20fDsjczgUidUBR8liPYU+WymTZP1lmY9G6Oc7HlZv156XqnsgNUzTyMefFTcsFH/tnJE/+xBg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<!-- css styles -->
<style>
    
    /* css variables - EDIT HERE */
    :root{
        --carousel-width: calc(640px / 2) ;
        --carousel-height: calc(420px / 2);
        --carousel-animation-time: 0.5s;
    }

    body{

        background-color: lightcoral;
        display: flex;
        justify-content: center;
    }

    /* container */
    .wrap{
        border: 10px black solid;
        display: inline-block;
        position: relative;
    }

    .wrap .carousel{
        
        /* positional properties */
        position: relative;

        /* box-model properties */
        height: var(--carousel-height);
        width: var(--carousel-width);
    }

    /* carousel shift controls  */
    .wrap .carousel .carousel__controls{
        
        /* display properties */
        display: flex;
        justify-content: space-between;

        /* positional properties */
        left: 0;
        position: absolute;
        top: 50%;
        z-index: 100;
   
        /* box-model properties */
        width: 100%;

        /* manipulation properties */
        transform: translateY(-50%);
    }
    
    .wrap .carousel .carousel__controls .controls__item {
       
        /* box-model properties */
        color: coral;
        font-size: 1.5rem;
        margin: 1rem 2rem;
    }

    .wrap .carousel .carousel__controls .controls__item:hover {

        /* box-model properties */
        color: burlywood;
        cursor: pointer;
    }


    /* carousel items */
    .wrap .carousel .carousel__list{
        
        /* positional properties */
        overflow: hidden;
        position: relative;

        /* box-model properties */
        background-color: burlywood;
        height: 100%;
        width: 100%;
    }
    
    .wrap .carousel .carousel__list .carousel__item{

        /* positional properties */
        position: absolute;
        top: 0;
        left: 0;

        /* box-model properties */
        width: 100%;
        height: 100%;
    }

    .wrap .carousel .carousel__list .carousel__item > img {

        /* box-model properties */
        height: var(--carousel-height);
        width: var(--carousel-width);
    }

    .wrap .carousel .carousel__list .carousel__item.active{

        /* positional properties */
        z-index: 90;

        /* manipualtion properties */
        transform: translateX(0%);    
    }

    .wrap .carousel .carousel__list .carousel__item.inactive-left{

        /* manipualtion properties */
        transform: translateX(0%);  
    }
    
    .wrap .carousel .carousel__list .carousel__item.inactive-right{

        /* manipualtion properties */
        transform: translateX(100%);  
    }


    /* carousel indicators */
    .wrap .carousel .carousel__indicators{
   
        /* positional properties */
        left: 50%;
        position: absolute;
        top: 90%;
        z-index: 100;

        /* manipualtion properties */
        transform: translate(-50%, -50%);
    }

    .wrap .carousel .carousel__indicators .indicator__item{
        
        /* box-model properties */
        color: lightgrey;
        margin: 0 0.5rem;
    }

    .wrap .carousel .carousel__indicators .indicator__item:hover{

        /* box-model properties */
        color: darkgrey;
    }

    .wrap .carousel .carousel__indicators .indicator__item.active{

        /* box-model properties */
        color: grey;
    }


    /* animations */
    .slide-left{

        /* positional properties */
        z-index: 90;

        /* animation properties */
        animation-duration: var(--carousel-animation-time);
        animation-fill-mode: forwards;
        animation-name: slide_left;
        animation-timing-function: ease-in-out;
    }

    @keyframes slide_left{
        0%{
            transform: translateX(0%);
        }
        100%{
            transform: translateX(-100%);
        }
    }

    .slide-from-right{

        /* positional properties */
        z-index: 90;

        /* animation properties */
        animation-duration: var(--carousel-animation-time);
        animation-fill-mode: forwards;
        animation-name: slide_from_right;
        animation-timing-function: ease-in-out;
    }

    @keyframes slide_from_right{
        0%{
            transform: translateX(100%);
        }
        100%{
            transform: translateX(0%);
        }
    }

    .slide-right{

        /* positional properties */
        z-index: 90;

        /* animation properties */
        animation-duration: var(--carousel-animation-time);
        animation-fill-mode: forwards;
        animation-name: slide_right;
        animation-timing-function: ease-in-out;
    }

    @keyframes slide_right{
        0%{
            transform: translateX(0%);
        }
        100%{
            transform: translateX(100%);
        }
    }

    
    .slide-from-left{

        /* positional properties */
        z-index: 90;

        /* animation properties */
        animation-duration: var(--carousel-animation-time);
        animation-fill-mode: forwards;
        animation-name: slide_from_left;
        animation-timing-function: ease-in-out;
    }

    @keyframes slide_from_left{
        0%{
            transform: translateX(-100%);
        }
        100%{
            transform: translateX(0%);
        }
    }

</style>

</head>
<body>

    <div class="wrap">

        <div class="carousel">

            <div class="carousel__controls">
                <i class="fa fa-chevron-left controls__item js-shift-left" aria-hidden="true"></i>
                <i class="fa fa-chevron-right controls__item js-shift-right" aria-hidden="true"></i>
            </div>

            <div class="carousel__list">  
            </div>

            <div class="carousel__indicators">
            </div>
        </div>
    </div>

<!-- javascript scripts -->
<script>

/*   
Tutorial Description

Sometimes it's necessary to show a sequence of images or "slides" to group content on your website without taking 
up too much space. Below is the code for a simple carousel slider.

1. Add the css in an external referenced .css file or in the header tag.

2. Add the javascript code in an external referenced .js file and reference it at the end of the body tag.

3. Add the html markup file to wherever you want your carousel gallery to be.

4. Modify the settings portion of the javascript file to add additional slide by adding more image sources.

5. Feel free to modify the carousel item css to fit your own needs. Enjoy.
*/

    /*
    *
    *  ADD carousel items HERE
    *  Format:
    *    {
    *       src : "url of image",  - mandatory
    *       state: "active" - optional but at least one object must have this field in order to have starting point
    *    }
    */
    const carousel_src = [
        {src : "http://www.javascriptfreecode.com/files/carousel-slider/pexels-ella-olsson-1640774.jpg", state: "active"},
        {src : "http://www.javascriptfreecode.com/files/carousel-slider/pexels-ella-olsson-1640777.jpg" },
        {src :"http://www.javascriptfreecode.com/files/carousel-slider/pexels-ella-olsson-3026808.jpg"},
        {src :"http://www.javascriptfreecode.com/files/carousel-slider/pexels-engin-akyurt-2673353.jpg"},
        {src :"http://www.javascriptfreecode.com/files/carousel-slider/pexels-senuscape-2313682.jpg"}
    ]


    /*
    *
    * @parms (number) timer - sets the animation duration for the javascript portion. 
    * Match the same as --carousel-animation-time value.
    *  
    */
    const timer = 500;
    let counter_item, counter_indicator;


    /*
    *
    * Initalizes the carousel user-interface based on the number of carousel items specified.
    * 
    */
    carousel_src.forEach((carousel_src, index) => {

        // populate carousel items
        const carousel_items_container = document.querySelector(".carousel__list");
        const item = carousel_src.hasOwnProperty("state") ? createElementWithClass("div", ["carousel__item", "active"])
        : createElementWithClass("div", ["carousel__item"]);

        item.style.backgroundImage = "url('" + carousel_src.src + "')";
        carousel_items_container.appendChild(item);

        // populate carousel indicators
        const carousel_indicators_container = document.querySelector(".carousel__indicators");
        const indicator = carousel_src.hasOwnProperty("state") ? createElementWithClass("i", ["fa","fa-circle", "indicator__item", "active"])
        : createElementWithClass("i", ["fa","fa-circle", "indicator__item"]);

        carousel_indicators_container.appendChild(indicator);

        // initiate counters for the items and indicators
        if(carousel_src.hasOwnProperty("state")){
            counter_item = counter_indicator = index;
        }
    });


    /**
     * Debounce function that ignores subsequent events until the timeout delay has passed
     * 
     * @param (function) func - reference to the function passed to be delayed.
     * @param (number) timeout - the timeout delay in milliseconds.
     * @returns
     */
    function debounce_leading(func, timeout = 500){

        let timer;

        return (...args) => {

            if (!timer) {
                func.apply(this, args);
            }

            clearTimeout(timer);

            timer = setTimeout(() => {
                timer = undefined;
            }, timeout);
        };
    }


    /**
     * Shifts carousel items to RIGHT
     * 
     * @param (string) typeName - string that specifies the element to be created.
     * @param (array) className - array of strings values that specifies the css classes to be added.
     * @param (string) content - string that specifies the text values to be added in the element.
     * @returns
     */
    function createElementWithClass(typeName, className, content ) {
        const element = document.createElement(typeName);

        if(Array.isArray(className)){

            if(className[0].length > 0){
                element.classList.add(...className);
            }

        }else{
            element.className = className;
        }

        if(content != undefined){
            element.innerHTML = content;
        }
        
        return element;
    }


    /**
     * Shifts carousel items to RIGHT
     * 
     * @param
     * @returns
     */
    function shift_right(){

        const curCounter = counter_item;
        counter_item++;

        carousel_items[curCounter].classList.add("slide-right");

        /* reset carousel counter to 0 when reaching end of items */
        if(counter_item == carousel_items.length){
            counter_item = 0;
        }

        carousel_items[counter_item].classList.add("slide-from-left");

        setTimeout( () => {

            carousel_items[curCounter].classList.remove("slide-right", "active");
            carousel_items[counter_item].classList.remove("slide-from-left");
            carousel_items[counter_item].classList.add("active");

            carousel__indicators[curCounter].classList.remove("active");
            carousel__indicators[counter_item].classList.add("active");
        }, timer);
    }


    /**
     * Shifts carousel items to LEFT
     * 
     * @param
     * @returns
     */
    function shift_left(){

        const curCounter = counter_item;
        counter_item--;
        
        carousel_items[curCounter].classList.add("slide-right");

        /* reset carousel counter to last item when reaching start of items array */
        if(counter_item < 0){
            counter_item = carousel_items.length - 1;
        }

        carousel_items[counter_item].classList.add("slide-from-left");

        setTimeout( () => {

            carousel_items[curCounter].classList.remove("slide-right", "active");
            carousel_items[counter_item].classList.remove("slide-from-left");
            carousel_items[counter_item].classList.add("active");

            carousel__indicators[curCounter].classList.remove("active");
            carousel__indicators[counter_item].classList.add("active");
        }, timer); 
    }


    /* 
    *
    * Add shift left and right event listeners
    *  
    */
    const carousel_items = document.querySelectorAll(".carousel__item");
    const carousel__indicators = document.querySelectorAll(".carousel__indicators > i");

    const carousel_shift_right = debounce_leading( () => shift_right());
    const carousel_shift_left = debounce_leading( () => shift_left());

    if(document.querySelector(".js-shift-right") != null){
        document.querySelector(".js-shift-right").addEventListener("click", carousel_shift_right);
    }

    if(document.querySelector(".js-shift-left") != null){
        document.querySelector(".js-shift-left").addEventListener("click", carousel_shift_left);
    }

</script>

</body>
</html><a target='_blank' href='https://www.javascriptfreecode.com' style='font-size: 8pt; text-decoration: none'>JavaScript Best Codes</a>                                                
                                            

Example:


About @phuang

Help desk analyst transitioning to a full-stack developer role. Hoping to learn and collaborate with everyone. Happy coding!

P

Comments


Here you can leave us commments. Let us know what you think about this code tutorial!

0 / 300

TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members: admin_js, bloxio, yqaice, flooketsu, phuang_test
advertisement 2