jQuery: Building a Simple Content Slider

 

  1. <!--HTML-->  
  2.   
  3. <div class="divMain">  
  4.     <div>Question 1</div>  
  5.     <div>Question 2</div>  
  6.     <div>Question 3</div>  
  7.     <div>Question 4</div>  
  8.     <div>Question 5</div>  
  9.     <div>Question 6</div      
  10. </div>  
  11. <button name="prev">Prev</button>  
  12. <button name="next">Next</button>  
  13.   
  14. <!--jQuery-->  
  15. $(document).ready(function () {  
  16.     var divs = $('.divMain>div');  
  17.     var now = 0;  
  18.     divs.hide().first().show();  
  19.     $("button[name=next]").click(function (e) {  
  20.         divs.eq(now).hide();  
  21.         now = (now + 1 < divs.length) ? now + 1 : 0;  
  22.   
  23.         if((now + 1) == divs.length)  
  24.             $(this).attr('disabled''disabled');  
  25.           
  26.         $("button[name=prev]").removeAttr('disabled');  
  27.         divs.eq(now).show(); // show next       
  28.     });  
  29.       
  30.     $("button[name=prev]").click(function (e) {  
  31.         divs.eq(now).hide();  
  32.         now = (now > 0) ? now - 1 : divs.length - 1;  
  33.         if(now == 0)  
  34.             $(this).attr('disabled''disabled');  
  35.               
  36.         $("button[name=next]").removeAttr('disabled');  
  37.         divs.eq(now).show(); // or .css('display','block');  
  38.     });  
  39. });  
  40.   
  41. <!--CSS-->  
  42.   
  43. .divMain {  
  44.     height:300px;  
  45.     border:1px solid #7C7C80;  
  46. }  
  47. .divMain>div {  
  48.     height:100%;  
  49.     overflow-y:auto;  
  50.     border:2px solid #AFA9DE;  
  51.     padding:1em;  
  52.     box-sizing:border-box;  
  53.     -moz-box-sizing:border-box;  
  54. }  
 This snippet shows how to build a content slider with previous and next button using jQuery. You can see the working demo here: http://jsfiddle.net/WGkPV/285/