A nifty little element slider

July 30, 2012

I created this nifty little slider for a product page and decided it was cool enough to share. Originally, I designed it to slide large, page-width, panels from left to right and back again, but it is easily be manipulated to achieve alternate effects.

Demo

Styling

Because I'm floating these elements and then simply scrolling back and forth, an overall holder is needed that keeps its overflow hidden.

<div id="holder">
	<div id="panels">
		<div class="panel blue"></div>
		<div class="panel yellow hide"></div>
		<div class="panel red hide"></div>
	</div>
</div>

<style>
#holder {
	overflow: hidden;
	position: relative;
	width: 500px;
}
#panels {
	position: relative;
}
.panel {
	float: left;
	height: 200px;
	width: 500px;
}
.blue {
	background: #01aef0;
}
.yellow {
	background: #FCD806;
}
.red {
	background: #D23A30;
}
.hide {
	display: none;
}
</style>

Javascript

$(function() {

var pageSlide = function() {	
	
	var wwth =  $('#panels').width(), // holder width
		pwth = (wwth * $('.panel').length), // total width of panels
		left = 0, // amount of css position
		on = 1, // current slide
		going = 'right'; // direction
	
	// set panels width
	$('#panels').css('width', pwth);
	
	// set width for individual items
	$('.panel').css('width', wwth); 
	
	$('.hide').show();
		
	this.slide = function() {
		
		var amount;
		
		if(on==$('.panel').length) {
			
			going = 'left';
		} else if(on==1) {
			
			going = 'right';
		}
		
		if(going=='right') {
			
			amount =  "-" + wwth
			++on;
		} else {
		
			amount =  wwth;
			--on;
		}
		
		// Figure out amount to move
		left = parseFloat(left) + parseFloat(amount);
		
		// Animate the move
		$('#panels').stop().animate({ left: left }, 500);
		
	}
	
	// Keep it going. This can also be cancelled by setting this to
	// null and returning to to the setInterval when you're ready
	// to resume.
	this.sliding = window.setInterval("this.slide()", 5000);
}

// Initial call
pageSlide();
});

That's it. Very simple and to the point. Could it be made better? Absolutely. Honestly, it doesn't necessarily need jQuery since I'm really only using it as a selector engine. It does make smaller tasks like setting and getting the styling a lot easier though.