Saturday, January 26, 2013

A Simple jQuery Slideshow Demo



In this example, we use previous and next buttons to control jQuery slideshow.
1) Create a div and list to define images:
     <div id="slideshow" >
    <ul>
        <li ><img src="1.jpg"  /></li>
        <li ><img src="2.jpg" /></li>
        <li ><img src="3.jpg"  /></li>    
    </ul>
    </div>
2) Define CSS to remove list style
    #slideshow ul, #slideshow li {
       margin:0;
       padding:0;
      list-style-type:none; 
    }
make image in fixed position, not float
    #slideshow li {
       position:absolute; 
    }
Three images have different size, maximum height 320px, define image layout
      #slideshow {
        height: 320px;
        top:0;
        left:0;
      }
4) Create two buttons
<button id="next">Next</button>
<button id="prev">Prev</button>
5) jQuery script:
   <script src="http://code.jquery.com/jquery-latest.min.js"></script>
 <script>
/* home slide show */
var slideUL = $('div#slideshow').children('ul');
var $slides =slideUL.find('img');
var slide_pos = 0;
var slide_len = $slides.length;
$slides.filter(':gt(0)').hide();
$('#next').click(function() {
    $slides.eq(slide_pos % slide_len).fadeOut(2000);
    $slides.eq(++slide_pos % slide_len).fadeIn(2000);
});
$('#prev').click(function() {
    $slides.eq(slide_pos % slide_len).fadeOut(2000);
    //less than 0 OK
    $slides.eq(--slide_pos % slide_len).fadeIn(2000);
});      
</script>
6) Demo:


Video for this demo

No comments:

Post a Comment