From a436c6f3a8c9f396c9f509a848873ed1987758e9 Mon Sep 17 00:00:00 2001 From: adroitwhiz Date: Fri, 31 Jul 2020 12:29:58 -0400 Subject: [PATCH] Make slider handles stick to the cursor --- src/components/forms/slider.jsx | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/components/forms/slider.jsx b/src/components/forms/slider.jsx index e4affea0..2d122d48 100644 --- a/src/components/forms/slider.jsx +++ b/src/components/forms/slider.jsx @@ -17,15 +17,21 @@ class SliderComponent extends React.Component { 'handleMouseUp', 'handleMouseMove', 'handleClickBackground', - 'setBackground' + 'setBackground', + 'setHandle' ]); + + // Distance from the left edge of the slider handle to the mouse down/click event + this.handleClickOffset = 0; } - handleMouseDown () { + handleMouseDown (event) { document.addEventListener('mousemove', this.handleMouseMove); document.addEventListener('mouseup', this.handleMouseUp); document.addEventListener('touchmove', this.handleMouseMove, {passive: false}); document.addEventListener('touchend', this.handleMouseUp); + + this.handleClickOffset = getEventXY(event).x - this.handle.getBoundingClientRect().left; } handleMouseUp () { @@ -41,20 +47,26 @@ class SliderComponent extends React.Component { } handleClickBackground (event) { + // Move slider handle's center to the cursor + this.handleClickOffset = HANDLE_WIDTH / 2; this.props.onChange(this.scaleMouseToSliderPosition(event)); } scaleMouseToSliderPosition (event){ const {x} = getEventXY(event); const backgroundBBox = this.background.getBoundingClientRect(); - const scaledX = x - backgroundBBox.left; - return Math.max(0, Math.min(100, 100 * scaledX / backgroundBBox.width)); + const scaledX = x - backgroundBBox.left - this.handleClickOffset; + return Math.max(0, Math.min(100, 100 * scaledX / (backgroundBBox.width - HANDLE_WIDTH))); } setBackground (ref) { this.background = ref; } + setHandle (ref) { + this.handle = ref; + } + render () { const halfHandleWidth = HANDLE_WIDTH / 2; const pixelMin = halfHandleWidth; @@ -76,6 +88,7 @@ class SliderComponent extends React.Component { >