How to make javascript custom carousel control

I am making a custom javascript carousel. I would like to make control of my carousel. I searched for an answer but couldn't find it.

here is the code i worked with

 <div class="container">
  <div class="row">
    <div class="col-lg-6 top-space text-center float">
      <h3 class="heading">Image Slider</h3>
      <hr>
    </div>
    <div class="col-lg-6 float">
      <img src="img/slider1.jpg" class="img-responsive" id="mainImage">
    </div>
  </div>
</div>

      

Javascript code:

 var imagesArray = ["img/slider2.jpg","img/slider3.jpg","img/slider4.jpg"];
 var index = 0 ;

 function imageSlider(){

   var getImagePath = document.getElementById("mainImage");
   getImagePath.setAttribute("src",imagesArray[index]);
   index++;

   if(index >= imagesArray.length){
     index = 0;
   }
}

setInterval(imageSlider,4000);

      

Here's a picture:

enter image description here

+3


source to share


2 answers


Here's an example:



function imageSlider(){
  this.prev = function(){
    if(--this.index < 0) this.index = this.imagesArray.length - 1;
    this.start()
  };

  this.next = function(){
    if(++this.index >= this.imagesArray.length) this.index = 0;
    this.start()
  };

  this.start = function(){
    var getImagePath = document.getElementById("mainImage");
    getImagePath.setAttribute("src", this.imagesArray[this.index]);

    this.timeout && clearTimeout(this.timeout);
    this.timeout = setTimeout(this.next.bind(this),3000)	
  };
}

var myCarousel = new imageSlider();
myCarousel.imagesArray = ["http://i.stack.imgur.com/d5vO7.jpg?s=128&g=1", "http://i.stack.imgur.com/GNgxX.png?s=128&g=1","http://i.stack.imgur.com/kpQYd.png?s=128&g=1"];
myCarousel.index = 0;
myCarousel.start()
      

<div class="container">
  <div class="row">
    <div class="col-lg-6 float">
      <img src="img/slider1.jpg" class="img-responsive" id="mainImage">
      <p><button onclick="myCarousel.prev()">Prev</button>
      <button onclick="myCarousel.next()">Next</button></p>
    </div>
  </div>
</div>
      

Run codeHide result


+1


source


The index must be incremented before specifying a new path. After that, just create a button that calls the imageSlider () function you created and the slider should go forward. If you don't want to do it back, you will need to create another function to do this. Something like:

   var getImagePath = document.getElementById("mainImage");
   index--;
   getImagePath.setAttribute("src",imagesArray[index]);


   if(index <= 0){
     index =  imagesArray.length - 1;
   }

      



To implement button functionality, you can use the jQuery.click () method: https://api.jquery.com/click/

or only use Javascript alternatives: http://www.w3schools.com/jsref/event_onclick.asp

0


source







All Articles