Hi Developers all over the world.
I would like to have some help with a simple, pure Javascript (30 lines), JQuery free (and other library\'s)
This code works in modern browsers. Just create some polyfill for that addEventListener
and this custom range slider will be safe to use:
function rangeSlider(id, onDrag) {
var range = document.getElementById(id),
dragger = range.children[0],
draggerWidth = 10, // width of your dragger
down = false,
rangeWidth, rangeLeft;
dragger.style.width = draggerWidth + 'px';
dragger.style.left = -draggerWidth + 'px';
dragger.style.marginLeft = (draggerWidth / 2) + 'px';
range.addEventListener("mousedown", function(e) {
rangeWidth = this.offsetWidth;
rangeLeft = this.offsetLeft;
down = true;
updateDragger(e);
return false;
});
document.addEventListener("mousemove", function(e) {
updateDragger(e);
});
document.addEventListener("mouseup", function() {
down = false;
});
function updateDragger(e) {
if (down && e.pageX >= rangeLeft && e.pageX <= (rangeLeft + rangeWidth)) {
dragger.style.left = e.pageX - rangeLeft - draggerWidth + 'px';
if (typeof onDrag == "function") onDrag(Math.round(((e.pageX - rangeLeft) / rangeWidth) * 100));
}
}
}
Demo: http://jsbin.com/dulifezi/2/edit
I’m creating a repo for this snippet here → https://github.com/taufik-nurrohman/range-slider