Jquery Image slider rotator slide show in horizontal direction made easy
Here you can see an image slider or in other words image rotator with animating effect using jquery. This is done very simply by using two div's and image tags and just three line of javascript code which uses jquery. The jquery code uses the default animate method to scroll the images horizontally. Images are displayed inline inside a div which will be fitting the total images width. This div is enclosed by another div which is of fixed with which will not show the scroll bar so overflow is hidden. and then we just scroll the inner div using javascript as if we use the scroll bar. with the help of the animate method of jquery we get the sliding effect.
Code and Explanation
You can also copy this code by viewing the source code of this page
<div class="contents" style="width:520px; margin:0px auto;"> <style>#_animateSam img{float:left;}</style> <script src="jquery-1.4.2.min.js"></script> <div id="_animateSam" style="width:500px; height:200px; overflow:hidden;"> <div style="width:2500px; height:295px;"> <img src="01.jpg" /><img src="02.jpg" /><img src="03.jpg" /> <img src="04.jpg" /><img src="05.jpg" /> </div> </div>
var _$cnt=1; function next() { $('#_animateSam').animate( {'scrollLeft':500*_$cnt++},500); if(_$cnt>4){_$cnt=0;} } window.setInterval('next()',3000)
- Create two div's. for example div one and div two.
- Width of div one will be equal to the width of an image.
- Width of div two should be the witdh of an image multiplied by the number of images which are going to be present inside that div(div two).
- Div one (_animateSam) is of fixed with and div to which is inside div sam is of variable width according to the number of images it is going to contain.
- See the style of div one which has been made as overflow:hidden.
- Though img tags are inline by default i made them float left. This worked so i am leaving it as floated left.
- And then i am calling a function using a timer which will scroll the inner div to a specific pixels. for example here the scroll value is the width of a single image.
- So eventually the first image will go left and the second image will be in view. And then incrementally untill the count has reached (no of images)-1. then i am making the count variable to zero so again the first image will come into view.
- The scroll left is done by the jquery method and property animate and scrollLeft respectively.
- Besides, it is all very clear from the code so you can just copy and paste and can do little modifications to suite to your needs.
That is all folks. Enjoy.
Comments, Suggestions, Objections, ...