Search code examples
javascripttouchaddeventlistenerdom-events

Toggling document touchmove on/off by adding / removing EventListener


I have a request to implement a lock/unlock function for body scrolling on mobile as follows :

var myObj = {
 disableBodyScroll: function() {
    document.querySelector('body').addEventListener("touchmove", function(e) {
      e.preventDefault();
      return false;
    }, 
    {passive: false}
    ); 
  },
  enableBodyScroll: function() {
    document.querySelector('body').removeEventListener("touchmove", function(e) {
      e.preventDefault();
      return false;
    }, 
    {passive: false}
    ); 
  }
}

when I do myObj.disableBodyScroll() it works fine. but myObj.enableBodyScroll() it doesn't and my scroll stays locked...

Any possible reason for this?

ref : https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener


Solution

  • I think it's because you don't pass the same listener function. Your enable and disable functions create both a new eventListener function. So the removeEventListener can't find the eventListener reference

    Try this :

    var myObj = {
            handleTouchMove: function (e) {
                e.preventDefault();
                return false;
            },
            disableBodyScroll: function() {
                document.querySelector('body').addEventListener("touchmove", myObj.handleTouchMove, {passive: false}
                );
            },
            enableBodyScroll: function() {
                document.querySelector('body').removeEventListener("touchmove", myObj.handleTouchMove, {passive: false}
                );
            }
        }