Search code examples
javascriptdom-eventsmouseup

MouseUp Event doesn't run after MouseDown


Trying to build a scrollbar that when you click and hold the mouse button and start to move along the Y-axis it is going to move the site up or down with some sensitivity. Everything is working fine, scrolling is smooth and works exactly I wanted. The problem is, that when you stop to hold the mouse button, it is still moving the site up and down on mouse move.

My Code

scrollbar.addEventListener("mousedown", scrollWhenMove);
body.addEventListener("mouseup", stopScroll);
function scrollWhenMove()
{
    scrollbar.addEventListener("mousemove", function() {onmove(event)})
    function onmove(event)
    {
        var moved = event.movementY;
        if(moved !== 0)
        {
            document.documentElement.scrollTop += (moved * 3);
        }
    }
}
function stopScroll()
{
        document.documentElement.scrollTop = 0;
        return false;
}

Any solutions?


Solution

  • You can use removeEventListener to stop listening to mouse move when stopScroll is called.

    However, note that it will only work if you pass it the same reference to the function that was passed in the previous addEventListener:

    // 2 different anonymous functions won't work
    scrollbar.addEventListener("mousemove", function() { onmove(); });
    scrollbar.removeEventListener("mousemove", function() { onmove(); });
    
    // OK, same reference
    scrollbar.addEventListener("mousemove", onmove);
    scrollbar.removeEventListener("mousemove", onmove);
    

    Demo:

    scrollbar.addEventListener("mousedown", scrollWhenMove);
    document.body.addEventListener("mouseup", stopScroll);
    
    function scrollWhenMove() {
      scrollbar.addEventListener("mousemove", onmove);
    }
    
    function stopScroll() {
      scrollbar.removeEventListener("mousemove", onmove);
    }
    
    function onmove(event) {
      var moved = event.movementY;
      if (moved !== 0) {
        document.documentElement.scrollTop += (moved * 3);
      }
    }
    img {
      display: block;
      max-width: 90%;
    }
    
    #scrollbar {
      position: fixed;
      top: 0;
      right: 0;
      width: 50px;
      height: 100%;
      background: #f00;
    }
    <img src="https://wvs.topleftpixel.com/photos/scotia_plaza_tall_stitched.jpg">
    
    <div id="scrollbar"></div>