Created
August 10, 2014 19:53
-
-
Save benshimmin/22a8dab214254978150d to your computer and use it in GitHub Desktop.
About the simplest way to make a draggable slider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* This will give you something to start with, anyway */ | |
.slider-container { | |
position : relative; | |
} | |
.track, .thumb { | |
position : absolute; | |
top : 0; | |
} | |
.track { | |
left : 10px; | |
width : 10px; | |
height : 400px; | |
background : #d0d0d0; | |
} | |
.thumb { | |
width : 30px; | |
height : 30px; | |
background : #aaa; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I offer this up mainly because it usually takes me a little bit of | |
// time to remember how to do this, not because it's particularly | |
// a glorious piece of code :-) | |
var $container, $thumb, $track; | |
$("body").append($container = $("<div>").addClass("slider-container")); | |
$container.append($track = $("<div>").addClass("track")); | |
$container.append($thumb = $("<div>").addClass("thumb")); | |
var clamp = function(num, min, max) { | |
return Math.max(min, Math.min(num, max)); | |
}; | |
// these should be the length of the track, plus or minus a bit | |
// if you want the thumb to go over the edge or whatnot | |
var min = 0, | |
max = 400; | |
$thumb.on("mousedown", function(event) { | |
var pos = parseInt($thumb.css("top"), 10), y = event.clientY; | |
$(document).on("mousemove.SLIDER_THUMB", function(event) { | |
$thumb.css("top", clamp(pos + (event.clientY - y), min, max)); | |
}); | |
$(document).on("mouseup.SLIDER_THUMB", function() { | |
$(document).off("mouseup.SLIDER_THUMB"); | |
$(document).off("mousemove.SLIDER_THUMB"); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment