Saturday, April 10, 2010

How to build a jQuery slideshow

A jQuery slideshow I can say it's the most used small application that you can integrate in a website.
There are many on the internet but the best practice is to create one of your own, by own custom rules.
I will show here a basic slideshow with slide effect:







 Here is a preview , we have numbers for each slide , left/right arrows and a click for details.

In this example images will have a custom width = 940px.


The jQuery code is :

var currentId = 1;
var currentScroll = 0;

$(document).ready(function() {
 // Load the slideshow
 imageRotator();
});

function imageRotator() {

 initialize();
 updateArrows(); 
 bindArrows();
 bindNumbers();

}

function initialize() {
 $('div#rotator ul').empty();
 currentId = 1;
 currentScroll = 0;

 documentWidth = $(window).width();
 $("#rotator #content").width(documentWidth-5);

 nrOfImages = $("div#rotator #content ul li").length;
 buildNumbers(nrOfImages);
 

 $("#rotator #content ul li a").each(function(i){
  $(this).css("left",820 + 940*i)
 
 });
}
function buildNumbers(nrOfImages) {
 $('#navbar').empty();
 var html = "";
 if (nrOfImages === 1) {
  html = "";
  $('#navbar').append(html);
 }
 else {
  for (var i = 1 ; i <= nrOfImages ; i++) {
   html += '



' + i + '
'; } $('#navbar').append(html); } } function bindArrows() { $('#leftArrow').click(function() { currentId--; currentScroll -= 940; changeSlide(); updateArrows(); }); $('#rightArrow').click(function() { currentId++; currentScroll += 940; changeSlide(); updateArrows(); }); } function bindNumbers(){ $('#navbar div').live('click',function() { var select = parseInt($(this).text()); currentScroll = 940 * (select - 1); changeSlide(); currentId = select; updateArrows(); }); } function changeSlide() { var current = $("#rotator #content"); current.animate ( { scrollLeft : currentScroll },1200) } function updateArrows() { changeSlide(); total_pictures = $('div#rotator #content1 ul li').length; if (currentId === total_pictures) { $('#rightArrow').hide(); } else { $('#rightArrow').show(); } if (currentId === 1) { $('#leftArrow').hide(); } else { $('#leftArrow').show(); } };

The html code is :

<div id = "content">
<ul>

ul>
div>
<div id="navbar">div>

 <div id="leftArrow">div>
<div id="rightArrow">div>
    div>
And inside ul you will have images
    Now you need to add css to display things as you want :)

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home