JavaScript to achieve a simple carousel effect

JavaScript to achieve a simple carousel effect

What is a carousel?

Carousel: In a module or window, you can see multiple pictures by clicking the mouse on a computer or sliding your finger on a mobile phone. These pictures are all carousel pictures, and this module is called the carousel module.

How to implement a carousel

How can I make a carousel in js, such as the one below, which can automatically generate small dots corresponding to the pictures, click the left and right arrows to jump to the previous or next picture, automatically rotate every few seconds, and you can also click the small dots to go to the specified picture.

HTML Structure

First, we create an HTML page. The structure is very simple. We use a large div to nest two divs and name it slider. The upper div is used to hold pictures and is named slider-img. The lower div is the control, which is used to hold buttons and small dots for the upper and lower pictures. It is called slider-ctrl.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="css/index.css"/>
    <script src="../public.js"></script>
    <script src="./js/index.js"></script>
</head>
<body>
    <div class="slider" id="slider">
        <div class="slider-img">
            <ul>
                <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/6.jpg" alt=""/></a></li>
            </ul>
        </div>
        <div class="slider-ctrl">
        //Automatically generate small dots here<span class="prev" id="prev"></span>
            <span class="next" id="next"></span>
        </div>
    </div>
</body>
</html>

CSS Code

The css code is very simple and brief.

* {
    margin: 0;
    padding: 0;
}
.slider {
    width: 310px;
    height: 265px;
    margin: 100px auto;
    position: relative;
    overflow: hidden;
}
.slider-img {
    width: 310px;
    height: 220px;
}
ul {
    list-style: none;
}
li {
    position: absolute;
    top: 0;
    left: 0;
}
.slider-ctrl {
    text-align: center;
    padding-top: 10px;
}
.slider-ctrl-con {
    display: inline-block;
    width: 24px;
    height: 24px;
    background: url(../images/icon.png) no-repeat -24px -780px;
    text-indent: -99999px;
    margin: 0 5px;
    cursor: pointer;
}
.slider-ctrl-con.current {
    background-position: -24px -760px;
}
.prev,.next {
    position: absolute;
    top: 40%;
    width: 30px;
    height: 35px;
    background: url(../images/icon.png) no-repeat;
}
.prev {
    left: 10px;
}
.next {
    right: 10px;
    background-position: 0 -44px;
}

js code

First, you need to do a demand analysis to clarify your thoughts, and then write the code step by step. We first get the relevant elements, and then generate corresponding small dots according to the number of pictures. Since the pictures are stacked together, we put the other pictures on the right to hide them and only display the first picture. Then you need to light up the first small dot to ensure that the small dot and the picture are bound together. Then we need to realize that clicking the right arrow can see the next picture, clicking the left arrow can see the previous picture, clicking the small dot can display the corresponding picture, and the corresponding pictures must be lit up. Finally, let it automatically rotate the pictures, stop the rotation when the mouse moves in, and continue the rotation when the mouse moves out

window.onload = function(){
    // 0 Get related elements // Total container var slider = document.getElementById('slider');
    // Collection of all pictures li var imgLiS = slider.children[0].children[0].children;
    //Container for control buttons var ctrlDiv = slider.children[1];
    //Left arrow (previous button)
    var prev = document.getElementById('prev')
    // Right arrow (next button)
    var next = document.getElementById('next')
    // container width var width = slider.offsetWidth;
    // Use a variable to record the index of the currently displayed image var index = 0;

    // 1 Generate corresponding small dots according to the number of pictures for(var i=imgLiS.length-1;i>=0;i--){
        var newPoint = document.createElement('span');
        // Record the node number of each node so that you can know the node number when you click it later newPoint.className = "slider-ctrl-con";
        newPoint.innerHTML = i;
        // Put it in the front ctrlDiv.insertBefore(newPoint,ctrlDiv.children[0])

        // 2 All pictures are placed on the right imgLiS[i].style.left = width+"px"
    }

    // 2 The carousel displays the first picture imgLiS[index].style.left = 0;

    // Get all the small dots var ctrlS = ctrlDiv.children;
    // 3 Light up the first dot light()

    // 4 Click the left arrow to view the previous picture and light up the corresponding dot prev.onclick = prevImg;

    // 5 Click the right arrow to view the next picture and light up the corresponding dot next.onclick = nextImg;

    // 6 Click on the small dot to light it up and display the corresponding picture for(var i=0;i<imgLiS.length;i++){
        ctrlS[i].onclick = function(){
            var num = +this.innerHTML;
            if(num>index){
                // I think the following picture is on the right imgLiS[num].style.left = width+"px";
                // Move the current image to the left move(imgLiS[index],'left',-width)
                // The picture I want to see goes to the middle move(imgLiS[num],'left',0)                
            }
            if(num<index){
                // I think the previous image is on the left imgLiS[num].style.left = -width+"px";
                // Move the current image to the right move(imgLiS[index],'left',width)
                // The picture I want to see goes to the middle move(imgLiS[num],'left',0)                
            }

            // Update index
            index = num;
            // Light up the dot light()
        }
    }

    // 7 can automatically rotate the picture: watch the next picture every 3 seconds var timer = setInterval(nextImg,3000)
    // 8 Move the mouse to stop the carousel slider.onmouseenter = function(){
        clearInterval(timer)
    }
    // 9 Move the mouse out to continue the carousel slider.onmouseleave = function(){
        clearInterval(timer)
        timer = setInterval(nextImg,3000)
    }
    
    
    
    // Since lighting up the dots is executed multiple times, encapsulate it into a function function light(){
        for(var i=0;i<imgLiS.length;i++){
            ctrlS[i].className = "slider-ctrl-con"
        }
        ctrlS[index].className = "slider-ctrl-con current"
    }

    //Function to look at the previous picture function prevImg(){
        var num = index-1;
        if(num<0){
            // The minimum index is 0. If the index you want to view is less than 0, it is the last picture, that is, the length-1th picture num = imgLiS.length-1;
        }
        // I think the previous picture must be on the left imgLiS[num].style.left = -width+"px";
        // The current image moves to the right move(imgLiS[index],'left',width)
        // Move the image to the middle move(imgLiS[num],'left',0)
        // After the movement is completed, the container displays the image num // So the value in the index that records the current index becomes num
        index = num;
        light()

    }

    // function to see the next picture function nextImg(){
        var num = index + 1;
        if(num>imgLiS.length-1){
            num = 0;
        }
        // I think the next one must be on the right imgLiS[num].style.left = width+"px";
        // Move the current image to the left move(imgLiS[index],'left',-width)
        // The next picture I want to see goes to the middle move(imgLiS[num],'left',0)
        // Update the value of index index = num;
        light()
    }

}

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:
  • 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
  • JS realizes automatic carousel effect (adaptive screen width + mobile phone touch screen sliding)
  • JS implements left and right seamless carousel code
  • Use html+js+css to achieve page carousel effect (example explanation)
  • Native js to achieve infinite loop carousel effect
  • js realizes the sliding carousel effect from left to right

<<:  How to install centOS8 in VMware12 (tutorial on installing centos8 in vm virtual machine)

>>:  VMware configuration hadoop to achieve pseudo-distributed graphic tutorial

Recommend

Docker+nextcloud to build a personal cloud storage system

1. Docker installation and startup yum install ep...

How to set up scheduled tasks in Linux and Windows

Table of contents Linux 1. Basic use of crontab 2...

Summarize the User-Agent of popular browsers

1. Basic knowledge: Http Header User-Agent User A...

How to modify the user and group of a file in Linux

In Linux, when a file is created, the owner of th...

Summary of mysqladmin daily management commands under MySQL (must read)

The usage format of the mysqladmin tool is: mysql...

Tips on setting HTML table borders

For many people who are new to HTML, table <ta...

In-depth explanation of currying of JS functions

Table of contents 1. Supplementary knowledge poin...

Vue+Vant implements the top search bar

This article example shares the specific code of ...

HTML basics summary recommendation (paragraph)

HTML Paragraph Paragraphs are defined by the <...

Interpretation of syslogd and syslog.conf files under Linux

1: Introduction to syslog.conf For different type...

Summary of several MySQL installation methods and configuration issues

1. MySQL rpm package installation # Download the ...

Several solutions for forgetting the MySQL password

Solution 1 Completely uninstall and delete all da...

Vue3 (III) Website Homepage Layout Development

Table of contents 1. Introduction 2. Actual Cases...

Native js to achieve star twinkling effect

This article example shares the specific code of ...