Creating Image Slide Show using jQuery:
In the code below you will see a surrounding div (id slideshow-area
) which holds our slideshow content scroll area and our next and previous buttons. Inside our scroll area we have a div to hold the content and finally the content itself. As far as html goes this is pretty simple stuff.
<div id=”slideshow-area”>
<div id=”slideshow-scroller”>
<div id=”slideshow-holder”>
<div class=”slideshow-content”>
<img src=”eureka_small.jpg” />
</div>
<div class=”slideshow-content”>
<img src=”wallace_gromit_small.jpg” />
</div>
<div class=”slideshow-content”>
<img src=”dead_like_me_small.jpg” />
</div>
</div>
</div>
<div id=”slideshow-previous”></div>
<div id=”slideshow-next”></div>
</div>
position
to relative
so that I can easily position the next and previous buttons absolutely.#slideshow-area, #slideshow-scroller {
width: 500px;
height: 500px;
position: relative;
overflow: hidden;
margin: 0 auto;
}#slideshow-area {
border: 1px solid #000;
}
500px
, same as the area.#slideshow-holder {
height: 500px;
}
#slideshow-previous, #slideshow-next {
width: 50px;
height: 50px;
position: absolute;
background: transparent url(“arrow_left.png”) no-repeat 50% 50%;
top: 225px;
display: none;
cursor: pointer;
cursor: hand;
}#slideshow-next {
display: block;
background: transparent url(“arrow_right.png”) no-repeat 50% 50%;
top: 225px;
right: 0;
}.slideshow-content {
float: left;
}
ready
event.var totalSlides = 0;
var currentSlide = 1;
var contentSlides = “”;$(document).ready(function(){
$(“#slideshow-previous”).click(showPreviousSlide);
$(“#slideshow-next”).click(showNextSlide);var totalWidth = 0;
contentSlides = $(“.slideshow-content”);
contentSlides.each(function(i){
totalWidth += this.clientWidth;
totalSlides++;
});
$(“#slideshow-holder”).width(totalWidth);
$(“#slideshow-scroller”).attr({scrollLeft: 0});
updateButtons();
});
showPreviousSlide
and showNextSlide
. These two functions do mainly three things: change current slide number, update the buttons, and scroll the content. These functions along with support functions are below.function showPreviousSlide()
{
currentSlide–;
updateContentHolder();
updateButtons();
}function showNextSlide()
{
currentSlide++;
updateContentHolder();
updateButtons();
}function updateContentHolder()
{
var scrollAmount = 0;
contentSlides.each(function(i){
if(currentSlide – 1 > i) {
scrollAmount += this.clientWidth;
}
});
$(“#slideshow-scroller”).animate({scrollLeft: scrollAmount}, 1000);
}function updateButtons()
{
if(currentSlide < totalSlides) {
$(“#slideshow-next”).show();
} else {
$(“#slideshow-next”).hide();
}
if(currentSlide > 1) {
$(“#slideshow-previous”).show();
} else {
$(“#slideshow-previous”).hide();
}
}