In this lesson I create click and drag functionality.
First I get 'slider' and initialise some variables: isDown = false, startX, scrollLeft.
I listen for the following events which I immediately invoke functions to:
-
slider
-
'mousedown', (e) => {}
First set 'isDown = true'. Then add an '.active' class to 'slider'.
Next set 'startX' to match the events 'e.pageX' coordinates. Subtracting the 'slider.offsetLeft' to anchor the value to the sliders position.
Set 'scrollLeft = slider.scrollLeft'
-
'mouseleave', () => {}
Set 'isDown = false'. Remove the class of '.active' from 'slider'.
-
'mouseup', () => {}
Set 'isDown = false'.
-
'mousemove', (e) => {}
Check if 'isDown' is false, if so, exit the function. Prevent the event from creating any default behaviour (e.preventDefault();).
Get where the cursor is. Set 'x' to 'e.pageX - slider.offsetLeft;'.
Calculate the 'walk' ((x - startX) * 3). The multiplier determines how many pixels to scroll for each pixel the user scrolls. Then set the 'slider.scrollLeft' (scrollLeft - walk).
See the Pen
JavaScript30 - 27 - Click And Drag by Corey Noble (@CoreyNoble)
on CodePen.