0

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
M. Gara
  • 1,023
  • 2
  • 14
  • 27

1 Answers1

1

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}
            );
        }
    }
Julien Bourdic
  • 1,398
  • 1
  • 12
  • 29
  • 1
    Thank you very much, my question is stricktly related to : https://stackoverflow.com/questions/10444077/javascript-removeeventlistener-not-working – M. Gara Apr 12 '19 at 14:43