Native js to achieve simple carousel effect

Native js to achieve simple carousel effect

This article shares the specific code of js to achieve a simple carousel effect for your reference. The specific content is as follows

The effect is as follows:

analyze:

Analysis results:

Analysis and implementation:

1. Get the big box (.carousel) containing the carousel through document.querySelector('.class name') , the parent element (.chevron) of the label containing the left and right buttons of the carousel, get the left and right buttons (.chevron-left, .chevron-right), get the parent element ul (.carousel-body) containing the carousel pictures [Note: here we get ul instead of li, because when the carousel is moved, the entire ul moves together], and finally get the li containing the carousel pictures (.indicators li)

//A big box for the carousel let oCarousel = document.querySelector('.carousel')
//The parent element of the label for the left and right buttons of the carousel let oChevron = document.querySelector('.chevron')
//Left button let oLeft = document.querySelector('.chevron-left')
//Right button let oRight = document.querySelector('.chevron-right')
//Get the parent element ul where the carousel image is placed
let oUl = document.querySelector('.carousel-body')
//Get the li that contains the carousel image
let oActives = document.querySelectorAll('.indicators li')

2. Click the left and right buttons to make the carousel image go to the previous or next picture:

First encapsulate an animation() function to facilitate multiple calls

function animation(obj,target){
    // Clear the timer clearInterval(obj.timer)
        obj.timer = setInterval(()=>{
            // Read the current position of the element let curX=obj.offsetLeft
 
            //Define a step size let step=10
            // Determine the direction to move (compare the size of the target position with the current position) 
            if(target<curX){
                step=-10
            }
            // According to the relationship between the current position, the target position, and the step length, // As long as the distance between the target position and the current position is less than the step length, the element's position is directly set to the target position if (Math.abs (target-curX) < Math.abs (step)) {
                obj.style.left=target+'px'
                clearInterval(obj.timer)
            }else{
                // Calculate the next step position let nextX=curX+step
                // Assign the next step position to obj.style.left
                obj.style.left=nextX+'px'
            }
        },10)
    }

①Because the left and right arrows in the carousel are hidden before the mouse moves into the carousel, they will be displayed when the mouse moves into the carousel. Therefore, it is necessary to bind the mouse in (onmouseover) and mouse out (onmouseout) events for the large box (.carousel) that holds the carousel.

oCarousel.onmouseover = function () {
        oChevron.style.display = "block"
    }
 
    oCarousel.onmouseout = function () {
        oChevron.style.display = "none"
    }

② Bind click events to the left and right buttons, define a counter global variable n, which represents the position of the image in the carousel. Because the size of a li here is 500px, set a global variable step size of 500 (the step size is the distance of each movement of ul in the carousel)

let n = 0
let step = 500
    oLeft.onclick = function () {
        n--
        
        if (n == -1) {
       //When you move to the first picture (n=0), click again (n=-1), set n to 4 and jump to the position of the last picture //The position of the ul containing the carousel picture is changed to the position of the last picture (because the width of a picture is 500px, so the last picture is at 5*500=2500)
            oUl.style.left = -2500 + 'px'
            n = 4
        }
        //target is the moving distance, that is: the nth picture * the width of each picture 
        let target = -n * step
        animation(oUl, target)
 
    }
    oRight.onclick = function () {
        n++
        if (n == 6) {
        //When you move to the last picture (n=5), click again (n=6), set n to 1 and jump to the position of the first picture oUl.style.left = 0 + 'px'
            n = 1
        }
        let target = -n * step
        animation(oUl, target)
 
    }

3. Click the number below to switch the carousel.

//Because the li obtained above through document.querySelectorAll('.indicators li') is returned in the form of a pseudo array, it is necessary to traverse the pseudo array to bind the click event for each li for (let i = 0; i < oActives.length; i++) {
        oActives[i].onclick = function () {
            //Set the style of the clicked item to highlight setActive(i)
            //And assign the value of i to n (equivalent to recording that the i-th picture should be displayed currently)
            n = i
            //Set the moving distance let target = -n * step
            animation(oUl, target)
        }
    }
 
    // Encapsulate a function to highlight li function setActive(ind) {
        //Use exclusive thinking: clear all, and then set the class name separately for (let j = 0; j < oActives.length; j++) {
            oActives[j].className = ''
        }
        oActives[ind].className = 'active'
    }

Modify the situation in step 2 where the highlight of the page below the slideshow remains unchanged when clicking the left and right arrows

oLeft.onclick = function () {
        n--
        if (n == -1) {
            oUl.style.left = -2500 + 'px'
            n = 4
        }
        //Call the setActive() function to modify the highlight status of the nth image page number setActive(n)
        let target = -n * step
        animation(oUl, target)
 
    }
    oRight.onclick = function () {
        n++
        if (n == 6) {
            oUl.style.left = 0 + 'px'
            n = 1
        }
        //If n is 5, it means that we have reached the 6th picture (the 6th picture is the same as the 1st picture, but it is used for sliding transition to prevent the effect of instantaneous jump), so we need to set the page number to 0 (the first picture) to highlight. //Here we use a ternary expression. If n is 5, set the 1st picture to highlight, otherwise set the nth picture to highlight. n == 5 ? setActive(0) : setActive(n)
        let target = -n * step
        animation(oUl, target)
 
    }

4. Set a timer, clear the timer when the carousel is moved in, and start the timer when it is moved out (to stop automatic playback when moving in, and start automatic playback when moving out)

//When loading the page, the timer should be turned on first, otherwise the carousel will not play automatically. It needs to wait for a move-in and move-out event to start the timer timer = setInterval(function () {
            //Call the click event oRight.onclick() bound to the right button
        }, 2000)
 
    //When the mouse moves in, display the left and right arrows and clear the timer oCarousel.onmouseover = function () {
        oChevron.style.display = "block"
        clearInterval(timer)
    }
 
    //When the mouse moves out, hide the left and right arrows and start the timer oCarousel.onmouseout = function () {
        oChevron.style.display = "none"
        timer = setInterval(function () {
            oRight.onclick()
        }, 2000)
    }

The complete code is as follows:

The CSS styles are as follows:

* {
     margin: 0;
     padding: 0;
        }
 
        .carousel {
            width: 500px;
            height: 200px;
            border: 1px solid red;
            margin: 100px auto;
            position: relative;
            overflow: hidden;
        }
        .carousel li {
            list-style: none;
        }
 
        /* Carousel content*/
        .carousel-body {
            width: 3000px;
            height: 200px;
            position: absolute;
        }
        .carousel-body li {
            list-style: none;
            float: left;
            width: 500px;
            height: 200px;
        }
 
        .carousel-body li img {
            width: 100%;
            height: 100%;
        }
 
 
        /* Left and right focus buttons */
        .carousel .chevron {
            position: absolute;
            top: 50%;
            height: 40px;
            width: 100%;
            transform: translateY(-50%);
            display: none;
        }
 
        .carousel .chevron-left,
        .carousel .chevron-right {
            width: 40px;
            height: 40px;
            background: #000;
            cursor: pointer;
            text-align: center;
            line-height: 40px;
            font-size: 30px;
            font-weight: bold;
            color: #fff;
            opacity: .3;
            border: 1px solid #fff;
        }
 
 
        .carousel .chevron-left {
            float: left;
            margin-left: 10px;
        }
 
 
        .carousel .chevron-right {
            float: right;
            margin-right: 10px;
        }
 
 
        /* 5.2 Carousel indicator structure*/
        .carousel .indicators {
            position: absolute;
            right: 30px;
            bottom: 20px;
        }
 
        .carousel .indicators li {
            float: left;
            width: 20px;
            height: 20px;
            margin-right: 10px;
            background: rgba(255, 255, 255, .8);
            text-align: center;
            line-height: 20px;
            cursor: pointer;
            color: rgba(0, 0, 0, .5);
        }
 
        .carousel .indicators li.active {
            background: #09f;
            color: red;
 }

The HTML is as follows:

<div class="carousel">
        <!-- Carousel content-->
        <ul class="carousel-body">
            <li><a href="#"><img src="./images/1.jpg" alt=""></a></li>
            <li><a href="#"><img src="./images/2.jpg" alt=""></a></li>
            <li><a href="#"><img src="./images/3.jpg" alt=""></a></li>
            <li><a href="#"><img src="./images/4.jpg" alt=""></a></li>
            <li><a href="#"><img src="./images/5.jpg" alt=""></a></li>
            <li><a href="#"><img src="./images/1.jpg" alt=""></a></li>
            <!-- a3.1 Add a new li that is the same as the first one-->
            <!-- <li><a href="#"><img src="./images/1.jpg" alt=""></a></li> -->
        </ul>
        <!-- Left and right focus buttons -->
        <div class="chevron">
            <div class="chevron-left">&laquo;</div>
            <div class="chevron-right">&raquo;</div>
        </div>
        <!-- 5.1 Carousel indicator structure-->
        <ol class="indicators">
            <li class="active">1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
        </ol>
</div>

js is as follows:

let oCarousel = document.querySelector('.carousel')
let oChevron = document.querySelector('.chevron')
let oLeft = document.querySelector('.chevron-left')
let oRight = document.querySelector('.chevron-right')
let oUl = document.querySelector('.carousel-body')
let oActives = document.querySelectorAll('.indicators li')
 
    let n = 0
    let step = 500
    let timer
    timer = setInterval(function () {
            oRight.onclick()
        }, 2000)
    oCarousel.onmouseover = function () {
        oChevron.style.display = "block"
        clearInterval(timer)
    }
 
    oCarousel.onmouseout = function () {
        oChevron.style.display = "none"
        timer = setInterval(function () {
            oRight.onclick()
        }, 2000)
    }
    oLeft.onclick = function () {
        n--
        if (n == -1) {
            oUl.style.left = -2500 + 'px'
            n = 4
        }
        setActive(n)
        let target = -n * step
        animation(oUl, target)
 
    }
    oRight.onclick = function () {
        n++
        if (n == 6) {
            oUl.style.left = 0 + 'px'
            n = 1
        }
        n == 5 ? setActive(0) : setActive(n)
        let target = -n * step
        animation(oUl, target)
 
    }
    for (let i = 0; i < oActives.length; i++) {
        oActives[i].onclick = function () {
            setActive(i)
            n = i
            let target = -n * step
            animation(oUl, target)
        }
    }
 
    // Encapsulate a function to highlight li function setActive(ind) {
        for (let j = 0; j < oActives.length; j++) {
            oActives[j].className = ''
        }
        oActives[ind].className = 'active'
    }
 
    function animation(obj,target){
        // Clear the timer clearInterval(obj.timer)
        obj.timer = setInterval(()=>{
            // Read the current position of the element let curX=obj.offsetLeft
 
            //Define a step size let step=10
            // Determine the direction to move (compare the size of the target position with the current position) 
            if(target<curX){
                step=-10
            }
            // According to the relationship between the current position, the target position, and the step length, // As long as the distance between the target position and the current position is less than the step length, the element's position is directly set to the target position if (Math.abs (target-curX) < Math.abs (step)) {
                obj.style.left=target+'px'
                clearInterval(obj.timer)
            }else{
                // Calculate the next step position let nextX=curX+step
                // Assign the next step position to obj.style.left
                obj.style.left=nextX+'px'
            }
        },10)
}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • JavaScript to implement simple carousel chart most complete code analysis (ES5)
  • Using js to achieve the effect of carousel
  • Using JavaScript to implement carousel effects
  • Implementing carousel effects with JavaScript
  • js to implement the complete code of the carousel
  • Sample code for implementing carousel with native js
  • js to achieve the effect of supporting mobile phone sliding switch carousel picture example
  • JS carousel diagram implementation simple code
  • js to achieve click left and right buttons to play pictures
  • JavaScript to implement the most complete code analysis of simple carousel (ES6 object-oriented)

<<:  Detailed installation and configuration tutorial of MySQL flashback tool binlog2sql

>>:  Detailed tutorial on running Tomcat in debug mode in IDEA Maven project

Recommend

Pricing table implemented with CSS3

Result: Implementation Code html <div id="...

How to set the default value of a MySQL field

Table of contents Preface: 1. Default value relat...

Summary of some common configurations and techniques of Nginx

Preface This article lists several common, practi...

How to control the startup order of docker compose services

summary Docker-compose can easily combine multipl...

What do CN2, GIA, CIA, BGP and IPLC mean?

What is CN2 line? CN2 stands for China Telecom Ne...

The complete code of the uniapp packaged applet radar chart component

Effect picture: The implementation code is as fol...

HTML line spacing setting methods and problems

To set the line spacing of <p></p>, us...

mysql command line script execution example

This article uses an example to illustrate the ex...

Use of Zabbix Api in Linux shell environment

You can call it directly in the Linux shell envir...

Pay attention to the use of HTML tags in web page creation

This article introduces some issues about HTML ta...

MySQL 8.0.12 Installation and Configuration Tutorial

This article records the detailed tutorial for in...

One sql statement completes MySQL deduplication and keeps one

A few days ago, when I was working on a requireme...

Detailed tutorial on installing PHP and Nginx on Centos7

As the application of centos on the server side b...