Alessandro Dotti Contra

Linux/Unix DevOps


JQuery scrolling slideshow

This is another slideshow effect implementation. Since the concept is quite similar to the one explained in the fading slideshow snippet, this time we will create a completely event driven (mouse click) slideshow.

HTML markup

<div id="slideshow">
	<div id="pictures">
	<img alt="Picture 00" src="img0.png"/>
	<img alt="Picture 01" src="img1.png"/>
	<img alt="Picture 02" src="img2.png"/>
	<img alt="Picture 03" src="img3.png"/>
	</div>
</div>

We have two distinct div containers. The first one, slideshow, will be our slideshow top layer; you can think of it as a paper sheet with a hole the size of the images to be displayed.

The second container, pictures, contains the actual pictures and will be sized to contain them all.

CSS snippet

#slideshow {
	width: 640px;
	height: 400px;
	overflow: hidden;
	position: relative;
}

#pictures {
	position: relative;
	height: 400px;
	width: 2560px;  // Combined size of all images
	left: 0;
	top; 0;
}

#pictures img {
	float: left;
}

As anticipated before, note how #slideshow and #pictures have been sized. Images have been declared as floats to remove margins and paddings between them.

Code snippet

function slideshow(target,container,duration) {
	//Target visibile area
	width = $(target).width();
	//How many images?
	images = $(container).find('img').length;
	//Which image are we displaying?
	current = Math.abs(parseInt($(container).css('left'),10) / width - 1);
	if(current < images) {
		//If this is not the last image scroll
		$(container).animate({'left':'-=' + width}, duration);
	} else {
		//Otherwise reset the slideshow
		$(container).animate({'left':0}, duration);
	}
}

What the slideshow() function does is pretty straigthforward: every time a user clicks on the slideshow, the function checks if the last image is displayed: if so the slideshow is reset, otherwise the next image is scrolled into view.

<script type="text/javascript">
$(document).ready(function() {
	$('#slideshow').click(function(){
		slideshow('#slideshow','#pictures',1000);
	});
});
</script>

And this snippet binds the function to the mouse click event.

View demo