I have created a custom code carousel with a custom scrollbar, navigation dots and buttons that is working properly when I navigate with Next/Prev Buttons. The problem is that I need to restrict the movement of the scrollbar because now is scrolling freely, everytime I drag the scrollbar everything stops working because the scrollbar stops in an indeterminate point. I’m struggling with this behaviour.
I need that, if I drag the scrollbar to the right, the next button function should be executed and the scrollbar should stop in the correct position and if I drag to the left the scrollbar should execute the Prev button function and should update the postion. Maybe someone could lend a hand. Thanks in advanced!
I have created this codepen to check the full example:
https://codepen.io/pixelmary/pen/PovBZZz
let flag_mouseDown = false;
let oldMousePosition = 0;
let oldAnchorPosition = 0;
scrollBarContainer.addEventListener('mousedown', function(e) {
if (e.target.nodeName === 'DIV') {
var distance = e.clientX - sliderViewbox.offsetLeft - anchor.offsetWidth / 2;
if (distance < 0) {
distance = 0;
} else if (distance + anchor.offsetWidth > containerWidth) {
distance = containerWidth - anchor.offsetWidth;
}
anchor.style.left = distance + 'px';
moveContent();
} else if (e.target.nodeName === 'SPAN') {
flag_mouseDown = true;
oldMousePosition = e.clientX;
oldAnchorPosition = anchor.offsetLeft;
}
});
scrollBarContainer.addEventListener('mouseup', function(e) {
flag_mouseDown = false;
oldMousePosition = e.clientX;
oldAnchorPosition = anchor.offsetLeft;
snapToNearestSlide();
});
scrollBarContainer.addEventListener('mousemove', function(e) {
if (!flag_mouseDown) {
return;
}
let distance = e.clientX - oldMousePosition;
let newPosition = oldAnchorPosition + distance;
if (newPosition < 0) {
newPosition = 0;
} else if (newPosition + anchor.offsetWidth > containerWidth) {
newPosition = containerWidth - anchor.offsetWidth;
}
anchor.style.left = newPosition + 'px';
moveContent();
});
const moveContent = function() {
let position = anchor.offsetLeft / (containerWidth - anchor.offsetWidth);
let newPosition = (0 - position * (contentWidth - containerWidth)) + 'px';
for (var i = 0; i < content.length; i++) {
content[i].style.marginLeft = newPosition;
}
};