English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Example Code of Carousel Implementation with Native JavaScript

Many websites have carousels, but it is difficult to find a systematic explanation. Therefore, this will give a simple introduction, hoping everyone can benefit. If there are any inaccuracies, everyone is welcome to point them out.

Principle:

Lay out some images in a row, then calculate the offset and use a timer to achieve timed rotation.

Step one: Establish the basic HTML layout

as shown below:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Carousel</title>
</head>
<body>
  <div class="container">
    <div class="wrap" style="left:-600px;">
      <img src="./img/5.jpg" alt="">
      <img src="./img/1.jpg" alt="">
      <img src="./img/2.jpg" alt="">
      <img src="./img/3.jpg" alt="">
      <img src="./img/4.jpg" alt="">
      <img src="./img/5.jpg" alt="">
      <img src="./img/1.jpg" alt="">
    </div>
    <div class="buttons">
      <span>1</span>
      <span>2</span>
      <span>3</span>
      <span>4</span>
      <span>5</span>
    </div>
    <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="arrow_left"><</a>/a>
    <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="arrow_right">></a>/a>
  </div>
</body>
</html>

 Only five images, but using7to achieve seamless looping, which will be detailed later.

And5a span, which allows us to see the current position of the carousel in real time.

Finally, there are two buttons that can be used to control the forward and backward navigation.

Here we need to use absolute positioning for the wrap, so we use left:-600px; to display the first image.

Step two: CSS layout

Firstly, resetcss, as shown below:

* {
      margin: 0;
      padding: 0;
    }
    a{
      text-decoration: none;
    }

Next, to ensure that the image is only within the container, we need to limit its width and height and use overflow: hidden; to hide the other images. We also want the wrap to move left and right relative to the container, so it is set to relative, as follows:

   .container {
      position: relative;
      width: 600px;
      height: 400px;
      margin:100px auto 0 auto;
      box-shadow: 0 0 5px green;
      overflow: hidden;
    }     

We set the wrap to absolute positioning, so we can control the movement of the image by controlling Left and Right. Set z-index:1; to serve as a reference for the buttons to be placed later. Since there are seven images, the width is4200px (for each image, we set600X400), we just need to let the image float to the left to fill a row.

    .wrap {
      position: absolute;
      width: 4200px;
      height: 400px;
      z-index: 1;
    }

Then we set the image to float to the left and limit its size, as shown below:

  .container .wrap img {
      float: left;
      width: 600px;
      height: 400px;
    }

The current effect is as follows:

    

At this moment, the first image has already been displayed and fills the entire container (container is a box-shadow's);

Then we put the buttons showing the order at the lower right corner of the pictures and set z-index:2; to ensure that buttons are above the pictures. 

    .container .buttons {
      position: absolute;
      right: 150px;
      bottom:20px;
      width: 100px;
      height: 10px;
      z-index: 2;
    }

Then we make a simple decoration for the span under buttons, and set an 'on' class for the span corresponding to the picture, as follows: 

    .container .buttons span {
      margin-left: 5px;
      display: inline-block;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background-color: green;
      text-align: center;
      color: white;
      cursor: pointer;
    }
    .container .buttons span.on{
      background-color: red;
    }

Next, we add the arrowheads for left and right switching, and then do some simple decoration. Note: because here we use entities to represent the left and right arrowheads, so we set font-size to change its size,

    .container .arrow {
      position: absolute;
      top: 35%;
      color: green;
      padding:0px 14px;
      border-radius: 50%;
      font-size: 50px;
      z-index: 2;
      display: none;
    }
    .container .arrow_left {
      left: 10px;
    }
    .container .arrow_right {
      right: 10px;
    }
    .container:hover .arrow {
      display: block;
    }
    .container .arrow:hover {
      background-color: rgba(0,0,0,0.2);
    }

Step 3: Add js logic

First, we get the wrap (because we need to set its left to control the carousel), then get the two arrowheads on both sides, and implement manual carousel play, as follows: 

 var wrap = document.querySelector(".wrap");
    var next = document.querySelector(".arrow_right");
    var prev = document.querySelector(".arrow_left");
    next.onclick = function () {
      next_pic();
    }
    prev.onclick = function () {
      prev_pic();
    }
    function next_pic () {
      var newLeft = parseInt(wrap.style.left)-600;
      wrap.style.left = newLeft + "px";
    }
    function prev_pic () {
      var newLeft = parseInt(wrap.style.left)+600;
      wrap.style.left = newLeft + "px";
    }

It is worth noting that here wrap.style.left is a string, so it needs to be converted to a number for calculation, and when setting left, it needs to be added with 'px' to become a string.

Now let's test it out:

 

You can see that at the first page, the left value is-600, so we can click the previous picture once, but when we click it again, a blank appears. Similarly, the next picture click, to-3600 is the last one, you can't click it anymore.  

That is to say, when we click the next picture to-3600px (which is the first picture) when we need to jump to the second picture next time, that is-1200px;so that the jump can be normal;

Similarly, when we click the previous picture to 0px (which is the fifth picture), we hope to jump to the fourth picture next time, that is-2400px;

Following this idea, we modify the next_pic and prev_pic functions as follows: 

    function next_pic () {
      var newLeft;
      if(wrap.style.left === "-3600px"){
        newLeft = -1200;
      }else{
        newLeft = parseInt(wrap.style.left)-600;
      }
      wrap.style.left = newLeft + "px";
    }
    function prev_pic () {
      var newLeft;
      if(wrap.style.left === "0px"){
        newLeft = -2400;
      }else{
        newLeft = parseInt(wrap.style.left)+600;
      }
      wrap.style.left = newLeft + "px";
    }

At this point, we can find that the pictures can be played in a loop!

However, at this time, we are manually cycling the play, and if we want to play automatically, we can use setInterval() as shown below: 

    var timer = null;
    function autoPlay () {
      timer = setInterval(function () {
        next_pic();
      },1000);
    }
    autoPlay();

That is, first set a timer, then create a function that can play automatically, and finally call this function. Now it can play automatically, and the effect is as follows:

  

But if we want to take a close look at one of the pictures, we hope the carousel stops playing, just use clearInterval() as follows:

    var container = document.querySelector(".container");
    container.onmouseenter = function () {
      clearInterval(timer);
    }
    container.onmouseleave = function () {
      autoPlay();  
    }

Now, as long as we move the mouse over the carousel, the carousel will not play. And after moving the mouse away, the carousel will play automatically.

However, as of now, the small dots below the carousel have not moved, and now we will implement it.

The principle is very simple, that is, set the initial index of buttons to 0, that is, the class of the first span is 'on', and then when the next_pic function is triggered, the index is incremented.1when the prev_pic function is triggered, index is reduced1and set the class of the current index small dot to on, which requires index to be a global variable to ensure that it is available in the scope of each function.

Add showCurrentDot function:

    var index = 0;
    var dots = document.getElementsByTagName("span");
    function showCurrentDot () {
      for(var i = 0, len = dots.length; i < len; i++){
        dots[i].className = "";
      }
      dots[index].className = "on";
    }

Add code in next_pic:

      index++;
      if(index > 4){
        index = 0;
      }

Add large size in prev_pic:

      index--;
      if(index < 0){
        index = 4;
      }
      showCurrentDot();

In this way, the carousel can automatically switch, and the small dots also change with the image.

However, this is still a certain distance from the carousel we often see - - - When clicking on a small dot, you can jump to the corresponding image. The implementation principle is: when clicking on a small dot, the Left of wrap becomes the corresponding value. The code is as follows:

 

 for (var i = 0, len = dots.length; i < len; i++){
      (function(i){
        dots[i].onclick = function () {
          var dis = index - i;
          if(index == 4 && parseInt(wrap.style.left)!==-3000){
            dis = dis - 5;   
          }
          //and as with prev and next, at the beginning photo5and the final photo1There may be problems when used, causing errors in symbols and digits. Just make the corresponding treatment.
          if(index == 0 && parseInt(wrap.style.left)!== -600){
            dis = 5 + dis;
          }
          wrap.style.left = (parseInt(wrap.style.left) + dis * 600)+"px";
          index = i;
          showCurrentDot();
        }
      })(i);      
    }

The principle is that when a small dot is clicked, the corresponding i value is obtained, which is also the index value of the span. We compare it with the global variable index, then reset the value of wrap.style.left, and then copy the i value to the global variable index, and finally display the current small dot. It is worth noting that: this involves the concept of closure, if you use a for loop directly, you cannot get the correct result.

The final effect is as shown in the figure:

  

The final code is as follows:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Carousel</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    a{
      text-decoration: none;
    }
    .container {
      position: relative;
      width: 600px;
      height: 400px;
      margin:100px auto 0 auto;
      box-shadow: 0 0 5px green;
      overflow: hidden;
    }
    .container .wrap {
      position: absolute;
      width: 4200px;
      height: 400px;
      z-index: 1;
    }
    .container .wrap img {
      float: left;
      width: 600px;
      height: 400px;
    }
    .container .buttons {
      position: absolute;
      right: 5px;
      bottom:40px;
      width: 150px;
      height: 10px;
      z-index: 2;
    }
    .container .buttons span {
      margin-left: 5px;
      display: inline-block;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background-color: green;
      text-align: center;
      color: white;
      cursor: pointer;
    }
    .container .buttons span.on{
      background-color: red;
    }
    .container .arrow {
      position: absolute;
      top: 35%;
      color: green;
      padding:0px 14px;
      border-radius: 50%;
      font-size: 50px;
      z-index: 2;
      display: none;
    }
    .container .arrow_left {
      left: 10px;
    }
    .container .arrow_right {
      right: 10px;
    }
    .container:hover .arrow {
      display: block;
    }
    .container .arrow:hover {
      background-color: rgba(0,0,0,0.2);
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="wrap" style="left: -600px;">
      <img src="./img/5.jpg" alt="">
      <img src="./img/1.jpg" alt="">
      <img src="./img/2.jpg" alt="">
      <img src="./img/3.jpg" alt="">
      <img src="./img/4.jpg" alt="">
      <img src="./img/5.jpg" alt="">
      <img src="./img/1.jpg" alt="">
    </div>
    <div class="buttons">
      <span class="on">1</span>
      <span>2</span>
      <span>3</span>
      <span>4</span>
      <span>5</span>
    </div>
    <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="arrow arrow_left"><</a>
    <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="arrow arrow_right">></a>
  </div>
  <script>
    var wrap = document.querySelector(".wrap");
    var next = document.querySelector(".arrow_right");
    var prev = document.querySelector(".arrow_left");
    next.onclick = function () {
      next_pic();
    }
    prev.onclick = function () {
      prev_pic();
    }
    function next_pic () {
      index++;
      if(index > 4){
        index = 0;
      }
      showCurrentDot();
      var newLeft;
      if(wrap.style.left === "-3600px"){
        newLeft = -1200;
      }else{
        newLeft = parseInt(wrap.style.left)-600;
      }
      wrap.style.left = newLeft + "px";
    }
    function prev_pic () {
      index--;
      if(index < 0){
        index = 4;
      }
      showCurrentDot();
      var newLeft;
      if(wrap.style.left === "0px"){
        newLeft = -2400;
      }else{
        newLeft = parseInt(wrap.style.left)+600;
      }
      wrap.style.left = newLeft + "px";
    }
    var timer = null;
    function autoPlay () {
      timer = setInterval(function () {
        next_pic();
      },2000);
    }
    autoPlay();
    var container = document.querySelector(".container");
    container.onmouseenter = function () {
      clearInterval(timer);
    }
    container.onmouseleave = function () {
      autoPlay();  
    }
    var index = 0;
    var dots = document.getElementsByTagName("span");
    function showCurrentDot () {
      for(var i = 0, len = dots.length; i < len; i++){
        dots[i].className = "";
      }
      dots[index].className = "on";
    }
    for (var i = 0, len = dots.length; i < len; i++){
      (function(i){
        dots[i].onclick = function () {
          var dis = index - i;
          if(index == 4 && parseInt(wrap.style.left)!==-3000){
            dis = dis - 5;   
          }
          //and as with prev and next, at the beginning photo5and the final photo1There may be problems when used, causing errors in symbols and digits. Just make the corresponding treatment.
          if(index == 0 && parseInt(wrap.style.left)!== -600){
            dis = 5 + dis;
          }
          wrap.style.left = (parseInt(wrap.style.left) + dis * 600)+"px";
          index = i;
          showCurrentDot();
        }
      })(i);      
    }
  </script>
</body>
</html>

 Summary:

It's not difficult to implement a carousel. The general idea is to first create a div, specify its width and height, and set overflow to hidden. Then create a div to hold the images, with a width equal to the total width of all images and make it float, so that all images are in a row. To achieve seamless scrolling, you need to add a transition image at the beginning and end. Add two buttons first to enable manual scrolling, and then add a timer to scroll automatically in one direction. Because users sometimes need to view details, the timer is cleared when the mouse enters and the timer is played again when the mouse slides out. To better user experience, we also added a row of small dots below, so users can clearly know their current position. Finally, by using closure, users can directly switch images by clicking on the small dots.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please send an email to notice#w (replace # with @) to report any issues, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You May Also Like