Content Sliders

by Puni Charana

HTML

<div id="gallery">
      
      <div id="slider">
          <div><h2>1</h2></div>
          <div><h2>2</h2></div>
          <div><h2>3</h2></div>
          <div><h2>4</h2></div>
      </div>
      <div id="navigation">
        <span id="prev">Prev</span>
        <span id="next">Next</span>
      </div>
      
    </div>

CSS

h2{font-size:25px; text-align:center;}


#gallery{ /* wrapper */
  margin: 0 auto;
  width: 200px;
}
#slider {
  width: 100%;
  height: 100px;
  position: relative;
  overflow: hidden;
  white-space:nowrap;
  font-size: 0;
}
#slider > div{
  width: 100%;
  height: 100%;
  background-color: #F19;
  display: inline-block;
  vertical-align: top;
  font-size: 1rem;
}
#prev, #next{
  width: 100px;
  height: 20px;
  float: left;
  background-color: #000;
  text-align: center;
  color: #fff;
  cursor: pointer;
}

JavaScript

jQuery(function ($) {
  
 var $gallery  = $("#gallery"),
     $slider   = $("#slider").scrollLeft(0),
     $slides   = $slider.find("> div"),
     n         = $slides.length,
     $prevNext = $("#prev, #next"),
     width     = $gallery.width(),
     delay     = 3000,
     c         = 0,
     itv;
 
  function anim() { 
      $slider.stop().animate({scrollLeft: width*c});
  }
  function stop() { 
      clearInterval(itv);
  }  
  function auto() { 
      itv = setInterval(function(){
          anim( ++c );
      }, delay);
  }

  $prevNext.click(function() {
      anim(c=(this.id==="next"?++c:--c)<0?n-1:c%n);
  });
  $gallery.hover(stop, auto);
  
  auto(); // Start!
     
});