SoFunction
Updated on 2025-04-10

JavaScript implementation image carousel component worth sharing

This article shares with you how to use JavaScript to implement picture carousel components for your reference. The specific content is as follows

Effect:

The picture is automatically played in a loop, and there is a button below to switch to the corresponding picture.
Add an animation to enable image switching.
When the mouse stops on the picture, the carousel stops, and two arrows on the left and right appear. Click to switch the picture.
When the mouse moves away from the picture area, continue the carousel from the current position.
Provide an interface that can set the carousel direction, whether to cycle, and interval time.
Click to view demo

Requirements for HTML and CSS:

<div class="carousel-box">
 <div class="carousel">
  <ul class="clearfix" >
   <li><img src="img/" alt=""></li>
   <li><img src="img/" alt=""></li>
   <li><img src="img/" alt=""></li>
   <li><img src="img/" alt=""></li>
   <li><img src="img/" alt=""></li>
   <li><img src="img/" alt=""></li>
  </ul>
 </div>
</div>

* It must be nested with two boxes, the innermost box needs to have an ul, and the picture needs to be included in the li.
*You can change the class name and replace the corresponding class name in the css file. Just pass in the correct DOM element when configuring the component.
*No limit on the image width and number, just change the value in the css file.

/* Values ​​that need to be changed*/
.carousel img{ 
 width: 600px;
 height: 400px;
}
.carousel,
.carousel-box {
 width: 600px; /*Single image width*/
 height: 400px; /*Single image height*/
}
.carousel ul{
 width: 3600px; /* Single picture width x number of pictures*/
}

principle:

Arrange all pictures horizontally, the outermost container and the wrapper container set overflow:hidden. The outermost container is used for the positioning of buttons and arrows. Use the scrollLeft property of the package container to control which image is displayed.

Ideas:

To implement these functions, there should be some methods:

1. Image switching function. Accepts a parameter to indicate the scrolling direction. Call the easing function to switch the picture. Call the toggle button icon function to light up the corresponding button.

2. Easing function.

3. Light up the button function.

4. Initialize the function. Used to bind events, create buttons and arrows, and initialize the initial position.

5. Create an arrow function.

6. Create button function.

7. Start the carousel function.

8. Carousel function.

9. Stop the function. Used to stop carousel.

Some morePublic Methods

$():Select the DOM element.

addClass(ele,"className"):Add class name to the element.

removeClass(ele,"className"):Removes the element's class name.

$.add(ele,"type",fun):Bind an event to a DOM node.

getCSS(ele,"prop"):Gets the value of the corresponding attribute of the element.

$.delegateTag("selector","tagName","type",fun):Event Agent.

accomplish:

Suppose there are 6 pictures, each picture has a width of 600px. Complete according to the independence of the function:

1. Easing function liner
The function of the easing function is to change the attribute value of the target element bit by bit until the target value is reached. The element that uses it may be a horizontal carousel picture, a vertical carousel picture, or a small box that wants to reach the right end of the page from the left end of the page. So it should receive four parameters (target element, attribute value to be changed, target value, number of movements).

liner=function(ele,prop,next,num){
 var speed=(next-ele[prop])/num,
  i=0;
 (function(){
  ele[prop]+=speed;
  i++;
  if (i<num) {
   setTimeout(,30);
  }
 })(); 
},

2. Light up the button function light
Lighting the button is essentially adding an active class to the button, and extinguishing the button is removing the active class to the button.

So how do you know which button is currently?

The easiest way is to get it directly, so you can add an index attribute to each button. When you need to light the button, you can pass the index of the button to light it to this function.

So how do you know which button to turn off?

The easiest way is to get it directly, so you can add a variable active at the end of the scope chain, remember the currently lit button, and this function can just turn it off.

light=function(index){
 removeClass(active,"active");
 active=$(+" "+"[index="+index+"]");
 addClass(active,"active");
}

3. Image switching function go
The value of the next scrollLeft needs to be calculated:

If it is moving to the left, scrollLeft should be -600. If it is already 0, switch to 3000. So it is ===0?width*(len-1):-width;

If you move to the right, scrollLeft should be +600, that is, 0—>600,600—>1200,..., 3000—>0. Here you can use judgment as above, or you can use a formula next=(cur+distance)%(distance*num). Right now(+width)%(width*len)

Need to get the index of the next button to be lit:

Just like the idea of ​​calculating scrollLeft, move to the left: index===0? len-1:index-1; move to the right: (index+1)%len

go=function(dire){
 var index=("index")-0,
  nextIndex,
  nextPosition;
 if (dire==="next") {
  nextIndex=(index+1)%len;
  nextPosition=(+width)%(width*len);
 }else{
  nextIndex=index===0? len-1:index-1,
  nextPosition====0?width*len:-width;
 }
 light(nextIndex);
 (ele,"scrollLeft",nextPosition); 
}

The len (total number of pictures), width (image width), and ele (wrap container) are also accessed by other functions, so they are also added to the end of the scope chain.

len=("img").length

width=parseInt(getCSS(("img")[0],"width");

ele=$(eleSelec), eleSelec is the selector for wrapping containers, such as .carousel

4. Create arrow function createArrow
Create a left-to-left arrow, bound the event handler function, for moving to the left. Create a right arrow, bound the event handler function, to move to the right.

createArrow=function(){
 var prev=("div"),
  next=("div");
 (("<"));
 ((">"));
 ="arrow prev";
 ="arrow next"; 
 (prev);
 (next);
 addClass(container,"hide");
 $.add(next,"click",function(){
  go("next");
 });
 $.add(prev,"click",function(){
  go("prev");
 });
}

The container represents the outermost container and is also accessed by other functions, so it is also added to the end of the scope chain.

container=$(wrapSelec), wrapSelec is the selector of the outermost container, such as .carousel-box

5. Create button function createBtn
Add an index to each button for light and turn off, and add a class name to the button group for style and get it:

createBtn=function(){
 var div=("div"),
  btns='';
 for(var i=0;i<len;i++){
  btns+='<a href="#" index="'+i+'"></a>';
 }
 =btns;
 addClass(div,"carousel-btn");
 (div);
}

6. Carousel function
Determine whether to call go("prev") or go("next") according to the requirements (clockwise, counterclockwise).

If you ask for a loop, call yourself again. If not looping, stop after one round of carousel.

So here we need a variable to judge the direction, a variable to judge whether it is looping, and a variable to count.

So four more variables are added to the end of the scope chain. direction, loop, count, begin is used to clear the timer.

circle=function(){
 count++;
 if (loop||count<len) {
  if (direction==="forward") {
   go("next");
  }else{
   go("prev");
  }
 }
 begin=setTimeout(,t);
}

7. Stop function stop

stop=function(){
 clearTimeout(begin);
}

8. Initialize function init
If it is the first time to use carousel, create buttons and arrows, and bind the button to the click event handler (get the clicked button index to light it up, switch to the corresponding picture), and then display the corresponding picture and buttons clockwise or counterclockwise.

So here needs to be added to the end of the scope chain to indicate whether it has been initialized.

init=function(){
 createBtn();
 createArrow();
 $.delegateTag(wrapSelec+" "+".carousel-btn","a","click",function(e,target){
  $.prevent(e);
  light(("index"));
  (ele,"scrollLeft",("index")*width);
 });
 $.add(container,"mouseenter",function(){
  stop();
  removeClass(container,"hide");
 });
 $.add(container,"mouseleave",function(){
  addClass(container,"hide");
  begin=setTimeout(circle,t); 
 });if (direction==="forward") {
  light(0);
 }else{
  light(len-1);
  =width*(len-1);
 }
 haveStart=true;
}

9. Start the carousel function start

This function is used as an interface to control the carousel direction, interval time, and whether to cycle. The counter is reset to zero.

Because the carousel may be repeated, the timer needs to be cleared before each start.

start=function(dir,th,lo){
 stop();
 count=0;
 direction=dir;
 t=th*1000;
 loop=lo;
 if (!haveStart) {
  init();
 }
 begin=setTimeout(circle,t);
}

At this point, all the functions that need to be used have been written. If you throw these functions and those required variables into a function, and pass the class name or ID of the outer container box wrapped in the container to it, this function returns an object containing the start and stop methods, and this component can be used.

But there is a problem, there is only one function, that is, a page can only have one carousel instance. Therefore, if you want a page to have two carousel instances using this component, you cannot throw them into a function. Then it can only be placed in the object. Each object has its own variable, and they share a set of methods.

Then, these variables cannot be accessed directly and need to be accessed through the object's properties, that is, this.

This will cause problems at this time. This will point to the environment where it is called, so when those variables are accessed in the event handler or in the timer, you cannot use this, but create a closure.

That is, when this can be obtained, assign this to a variable, and then access this variable in the event handler or timer, the correct object will be obtained.

Take the init function as an example to modify:

=function(){
 var that=this;
 ();
 ();
 $.delegateTag(+" "+".carousel-btn","a","click",function(e,target){
  $.prevent(e);
  (("index"));
  (,"scrollLeft",("index")*);
 });
 $.add(,"mouseenter",function(){
  ();
  removeClass(,"hide");
 });
 $.add(,"mouseleave",function(){
  addClass(,"hide");
  =setTimeout(function(){
   ();
  },); 
 });if (==="forward") {
  (0);
 }else{
  (-1);
  =*(-1);
 }
 =true;
};

In this way, after the modification is completed, an instance can be created. Each instance will have its own attributes for recording the state, and they all share the methods in the prototype.

If you adopt prototype inheritance, you can create an object as a prototype object for the instance, and then create a function to produce the instance:

var carouselProto={};

//Give the above methods to this object=...
=...
=...

//Create instance object functionvar carousel=function(eleSelec,wrapSelec){
 var that=(carouselProto);
 =wrapSelec;
 =$(eleSelec);
 =$(wrapSelec);
 =("img").length;
 =parseInt(getCSS(("img")[0],"width"));
 return that;
}

//Create an instance and use componentsvar carousel1=carousel(".carousel",".carousel-box");
  ("forward",3,true);
var carousel2=carousel(".carousel2",".carousel-box2");
  ("backward",2,true);

Performance optimization:

1. When the clicked button happens to be the currently lit button, light and will still be called once. So you can add a judgment statement. If the button you clicked happens to be correct, don’t execute the following.

$.delegateTag(+" "+".carousel-btn","a","click",function(e,target){
 $.prevent(e);
 var index=("index");
 if (index===("index")) {
  return
 }
 (index);
 (,"scrollLeft",("index")*);
});

2. When the picture is switched, the easing animation is being executed. If you click the button or arrow before the easing animation is executed, it will enter the next animation, and chaos will occur and the picture will be misaligned. Performance will also be affected. To prevent this from happening, a variable can be used to record whether the easing animation is being executed. If it is not executed, clicking the button or arrow will execute the function.

liner=function(ele,prop,next){
 var speed=(next-ele[prop])/10,
  i=0;
 =true;
 (function(){
  ele[prop]+=speed;
  i++;
  if (i<10) {
   setTimeout(,60);
  }else{
   =false;
  }
 })(); 
}
if (!) {
 (nextIndex);
  (,"scrollLeft",nextPosition);
}

Click to viewSource code

Reference resources:

MOOC.com—Focus image carousel effects
《JavaScript:The Good Parts》

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.