Sample Code for implementing the image carousel component using JavaScript

Source: Internet
Author: User
Sample Code for JavaScript Implementation of the image carousel component this article introduces the JavaScript Implementation of the image carousel component. If you don't talk much about it, simply look at the following:

Effect:

Requirements for HTML and CSS:

The two boxes must be nested. the innermost box must have a ul, and the picture must be contained in li.

You can change the class name and replace the corresponding class name in the css file. Enter the correct DOM element when configuring the component.

Without limiting the image width and quantity, you can change the value in the css file.

/* Value to be changed */. carousel img {width: 600px; height: 400px ;}. carousel ,. carousel-box {width: 600px;/* width of a single image */height: 400px;/* height of a single image */}. carousel ul {width: 3600px;/* width of a single image x number of images */}

Principle:

Arrange all the images horizontally. Set overflow: hidden for the outermost container and package container. The outermost container is used to locate buttons and arrows. Use the scrollLeft attribute of the package container to control which image is displayed.

Ideas:

To implement these functions, you should use the following methods:

1. Image switching function. Accept a parameter to indicate the scroll direction. Call the easing function to switch images. Call the switch 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 a button function.

7. Start the carousel function.

8. Carousel function.

9. Stop the function. Used to stop carousel.

There are also some common methods: $ (): select the DOM element. AddClass (ele, "className"): adds a class name to the element. RemoveClass (ele, "className") removes the Class Name of the element. $. 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 proxy.

Implementation:

Suppose there are 6 images with a width of PX. Perform the following operations based on the independence of functions:

1. Easing function liner

The easing function is used to change the attribute value of the target element at until the target value is reached. Its elements may be horizontal carousel images, vertical carousel images, or a small box to reach the right of the page from the left side of the page. Therefore, it should receive four parameters (the target element, the attribute value to be changed, the target value, and the number of moves ).

Liner = function (ele, prop, next, num) {var speed = (next-ele [prop])/num, I = 0; (function () {ele [prop] + = speed; I ++; if (I
 
  

2. light Function

In essence, the light button adds an active class to the button, and the off button removes the active class from the button.

So how can we know which button is the current one?

The simplest method is to obtain the index directly. Therefore, you can add an index attribute for each button. When you need to light up the button, you can pass the index of the button to be lit to this function.

So how do you know which button to extinguish?

The simplest method is to directly obtain the variable, so you can add an active Variable at the end of the scope chain and remember the button that is currently on. This function can simply turn it out.

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

3. Image switching function go

Calculate the value of the next scrollLeft:

If it is to move to the left, scrollLeft should be-600. If it is already 0, it will be switched to 3000. So it is ele. scrollLeft = 0? Width * (len-1): ele. scrollLeft-width;

If it is to move to the right, scrollLeft should be + 600, that is, 0 --> 600,600 --> 1200,..., 3000 --> 0. Here we can use the formula "next = (cur + distance) % (distance * num)" as shown above ). (Ele. scrollLeft + width) % (width * len)

You need to obtain the index of the next button to be lit:

Moving to the left is the same as calculating scrollLeft: index = 0? Len-1: index-1; move to right :( index + 1) % len

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

Len (total number of images), width (image width), and ele (package container) are also accessed by other functions, so they are also added to the end of the scope chain.

Len = ele. getElementsByTagName ("img"). length

Width = parseInt (getCSS (ele. getElementsByTagName ("img") [0], "width ");

Ele = $ (eleSelec), eleSelec is the selector of the packaging container, such as. cancusel

4. Create the arrow function createArrow

Create an arrow to the left and bind it to the event handler function to move it to the left. Create an arrow to the right and bind it to the event handler function to move it to the right.

createArrow=function(){  var prev=document.createElement("p"),    next=document.createElement("p");  prev.appendChild(document.createTextNode("<"));  next.appendChild(document.createTextNode(">"));  prev.className="arrow prev";  next.className="arrow next";    container.appendChild(prev);  container.appendChild(next);  addClass(container,"hide");  $.add(next,"click",function(){    go("next");  });  $.add(prev,"click",function(){    go("prev");  });}

Container represents the outermost container and will be accessed by other functions. Therefore, it is added to the end of the scope chain.

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

5. Create the button function createBtn

Add an index for each button to light up and off, and add a class name for the button group to set the style and get it:

CreateBtn = function () {var p = document. createElement ("p"), btns = ''; for (var I = 0; I
   
    

6. Carousel Functions

Determine whether to call go ("prev") or go ("next") as required (clockwise or counterclockwise ").

If loop is required, call yourself again. If there is no loop, it stops after one round of carousel.

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

Therefore, four other variables are added to the end of the scope chain. Direction, loop, count, and begin are used to clear the timer.

Circle = function () {count ++; if (loop | count
     
      

7. stop the function stop

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

8. initialize the init function.

If carousel is used for the first time, create a button and an arrow, and bind a click event handler to the button (obtain the clicked index to light it and switch to the corresponding image ), then, the corresponding images and buttons are displayed clockwise or counterclockwise.

Therefore, we need to add a variable to the end of the scope chain to indicate whether the variable has been initialized.

init=function(){  createBtn();  createArrow();  $.delegateTag(wrapSelec+" "+".carousel-btn","a","click",function(e,target){    $.prevent(e);    light(target.getAttribute("index"));    animate.liner(ele,"scrollLeft",target.getAttribute("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);    ele.scrollLeft=width*(len-1);  }  haveStart=true;}

9. start the carousel Function

This function is used as an interface to control the carousel direction, interval, and loop. Returns the counter to zero.

The timer must be cleared before each start because the carousel may start repeatedly.

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

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

However, there is one problem. This function has only one function, that is, one page can only have one carousel instance. Therefore, if you want two carousel instances to use this component on a page, you cannot throw them into a function. You can only put it in the object. Each object has its own variables and they share a set of methods.

Then, these variables cannot be accessed directly, and they must be accessed through the attributes of the object, that is, this.

This will cause a problem. this will point to the environment that calls it. So when the variables are accessed in the event handler or in the timer, this cannot be used, instead, create a closure.

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

Using the init function as an example:

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

After the modification, you can create an instance. Each instance has its own properties to record the status. They all share the methods in the prototype.

If prototype inheritance is used, you can create an object as the prototype object of the instance, and then create a function to produce the instance:

Var incluuselproto ={}; // give the above methods to this object using uselproto. light =... extends uselproto. go =... extends uselproto. stop =... // create an instance Object function var incluusel = function (eleSelec, wrapSelec) {var that = Object. create (export uselproto); that. wrapSelec = wrapSelec; that. ele = $ (eleSelec); that. container = $ (wrapSelec); that. len = that. ele. getElementsByTagName ("img "). length; that. width = parseInt (getCSS (that. ele. getElementsByTagName ("img") [0], "width"); return that;} // create an instance and use the var component usel1 = usel (". carousel ",". carousel-box "); carousel1.start (" forward ", 3, true); var carousel2 = carousel (". carousel2 ",". carousel-box2 "); carousel2.start (" backward ", 2, true );

Performance Optimization:

1. When the clicked button is the current highlighted button, light and animate. liner will still be called once. Therefore, you can add a judgment statement. If the button you click is correct, do not execute the following statement.

$.delegateTag(this.wrapSelec+" "+".carousel-btn","a","click",function(e,target){  $.prevent(e);  var index=target.getAttribute("index");  if (index===that.active.getAttribute("index")) {    return  }  that.light(index);  animate.liner(that.ele,"scrollLeft",target.getAttribute("index")*that.width);});

2. When the image is switched, the animation is being executed. If you click a button or arrow before the animation is executed, the animation enters the next animation, causing chaos and misplacement. Performance is also affected. To prevent this, you can use a variable to record whether the animation is being executed. If the animation is not executed, click the button or arrow to execute the function.

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.