I created a custom content scroll box using HTML, CSS and JavaScript. When you try to drag the scrollbar it jumps to the left edge of the scrollbar. Any idea why am I missing something?
var scrollbar = document.getElementById("scrollbar");
var barWidth = 300;
var scrollbarWidth = 40;
scrollbar.addEventListener("mousedown", function(e) {
window.addEventListener("mousemove", hScroll, null);
}, null)
window.addEventListener("mouseup", function(e) {
window.removeEventListener("mousemove", hScroll, null);
}, null);
function hScroll(e) {
var scroller_pos = e.clientX - offset;
if (scroller_pos <= 0) scroller_pos = 0;
else if (scroller_pos >= barWidth-scrollbarWidth) scroller_pos = barWidth-scrollbarWidth;
scrollbar.style.marginLeft = scroller_pos + "px";
}
On mousedown you should calculate the offset between the distance of the square from the
bar‘s left edge and the distance of the mouse x position from the same edge. Then on move you should add this to the new position of the square.