jQuery: animated slider

In this post I'm going to show you how to implement an animated slider with jQuery. To accomplish this task without using jQuery UI, we need to keep track of the mouse coordinates within a given element. Done that, we can move our target element horizontally using the animate() method. First of all, we need a basic HTML structure to work with and some CSS styles:

<div id="container">
	<div id="test"></div>
</div>
<div id="tracker">
	<div id="track"></div>
</div>
body {
	margin: 0;
	padding: 0;
}

#container {
	width: 100%;
	height: 150px;
	background: orange;
}

#test {
	width: 20px;
	height: 150px;
	background: #000;
	position: relative;
	cursor: move;
	border-radius: 6px 6px 0 0;
}
#tracker {
	width: 100%;
	height: 20px;
}
#track {
	height: 20px;
	width: 20px;
	background: gray;
	position: relative;
	border-radius: 0 0 6px 6px;
}

Now jQuery: Both the tracker and the target element should move together when a user releases the mouse button. Here's how we can do:

$(document).ready(function() {

   $('#container').bind('mouseup', function(e) {

       var left = e.pageX - this.offsetLeft;

       $('#test').animate({left: left}, 500).parent().next().find('#track').animate({left: left}, 500);

   });

});

We use the mouseup event here together with the pageX and offsetLeft properties to exactly track the movements of the mouse. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.