Carousel

Here is a little javascript/jQuery carousel I knocked up this morning. It's an extension of something I put together for a recent project, seen here in dev form. Today I put the functionality in to stop the click function at the beginning and the of the list of carousel items. I thought I'd note it down here.

  • One
  • Two
  • Three
  • Four
  • Five
  • Six
  • Seven
  • Eight
Count downCount up
Source of the javascript:
1  $(function() {
2	
3  myCarousel = function() {
4		
5 	var scrollContent = $("div.inner-cont ul"); //the content to be scrolled
6	var pixelShift = 0;
7	var liCount = $("div.inner-cont ul li").size(); //count the number of list items
8	var marginVal = 158;
9	var rightLink = $("div.rot-cont a.right");
10	var leftLink = $("div.rot-cont a.left");
11
12	rightLink.click(function() {
13		var liTotalCount = 0 - liCount * marginVal; //total length in pixels, in this case 158 x the number of list items, subtracted from zero, this is to store the variable as a number not a string
14		var stopCount = liTotalCount + marginVal; //add one width to the total, so that we stop on the last list item
15		if (pixelShift != stopCount) {
16			pixelShift = pixelShift - marginVal; //shift by 158px on every click
17			scrollContent.animate({'left': pixelShift + 'px'}, 'slow'); //animate the shift
18			return false; //disable the anchor
19		}
20		else {
21			return false; //else (we're at the end), disable the anchor and do nothing
22		}
23	});
24
25	leftLink.click(function(event) { //same again, but for the count down link
26		if (pixelShift != 0) {
27			pixelShift = pixelShift + marginVal;
28			scrollContent.animate({'left': pixelShift + 'px'}, 'slow');
29			return false;
30		}
31		else {
32			return false;
33		}
34	});
35 }
36	
37 myCarousel();
38
39 });

It uses a variable (marginVal) for the list item width in pixels (this should match the width in the CSS), so ultimately it can have as many or as few list items to scroll through as you like.

I can't be bothered to pick it apart any further, the comments should explain enough, and view the source of the post to see the HTML/CSS but feel free to drop me a line if you have any questions or comments.

Recent Posts