Horizontal Scroll With Mouse Javascript

Code Snippets 4 U

The example code was written for React component.

Take two variables

touchableWrapper = null;
scroll = false;

Function that handles events:

 // handles the scrolling of horizontally placed elements (using flex and scrollbar hidden)
    mouseDown = (e) =>{
        let clientX = e.clientX;
        let clientY = e.clientY;
        let maxScroll = this.touchableWrapper.scrollWidth;
        // get the boundary of parent div
        // if the mouse is within those then allow scroll by setting this.scroll to true
        let parentBoundary = this.touchableWrapper.getBoundingClientRect();
        if(clientX > parentBoundary.left || clientX < parentBoundary.right) {
            this.scroll = true;
        }
        if(clientY > parentBoundary.top || clientY < parentBoundary.bottom) {
            this.scroll = true;
        }
        // Update the clientX as the mouse moves.
        let clientXNew = clientX;
        document.onmousemove = (e) => {
            if(this.scroll)
                clientXNew = e.clientX;
        }

        // Update the clientX as the internal elements are dragged.
        document.ondragend = (e) => {
            if(this.scroll){
                clientXNew = e.clientX;
                scroller();
            }
        }

        // call the scroller when the mouse is up
        // it is called only when onmousemove event is fired and not in case of ondragend
        document.onmouseup = () => {
           scroller();
        }

        // handles scrolling
        let scroller = () => {
            if(!this.scroll) return;
            this.scroll = false; // reset scroll
            let toScroll = 0;
            if(clientX > clientXNew){
                toScroll = this.touchableWrapper.scrollLeft + (clientX-clientXNew);
            }
            else{
                toScroll = this.touchableWrapper.scrollLeft - (clientXNew-clientX);
            }
            // handle negative and surplus toScroll
            if(toScroll < 0) {
                toScroll = 0;
            }
            else if(toScroll > maxScroll) {
                toScroll = maxScroll;
            }
            this.touchableWrapper.scrollLeft = toScroll;
        }
    }

JSX :

<div 
  ref={c=>this.touchableWrapper = c} 
  onMouseDown={this.mouseDown} >
  <div>
      {this.props.children}
  </div>
</div>

Use below css on parent for better UI

user-select: none;
-webkit-user-drag: none;

Leave a Reply

Your email address will not be published. Required fields are marked *

− one = six