4

I am recently run into a problem to prevent touch move event on the browser.

I have done it by document.ontouchmove

but i wasn't been able to do the same with document.addEventListener("touchmove")

just wondering what's the difference between two.

why first one works on the mobile but addEventListner don't.

Bill
  • 17,872
  • 19
  • 83
  • 131
  • 8
    `document.ontouchmove` is a property. If you set its value twice, only last value will be retained. `document.addEventListener` adds listeners to event. So all values are preserved – Rajesh Dec 19 '18 at 09:29
  • 4
    Interesting topic, when you run ```addEventListener```, you can assign multiple methods to some event/action. If you do it directly, i.e. ```el.onclick = ...``` then that can be over-ridden at a later date. Rajesh kinda beat me to it though... – JO3-W3B-D3V Dec 19 '18 at 09:30
  • @Rajesh yea, i notice that, but why and when you should use document.on – Bill Dec 19 '18 at 09:30
  • 4
    @Bruce, it's okay to use ```document.on..``` when you know you only want one method for that event, and that will be the only method, period. IMO it's a safer bet to just use ```addEventListener```, if at a later date you want to do some other ```onWhatever``` event handler, it's no issue. – JO3-W3B-D3V Dec 19 '18 at 09:31
  • 3
    @Bruce a related article but in reference to click function: https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick. Hope it helps – Rajesh Dec 19 '18 at 09:32

1 Answers1

1

May be the case.

// Case 1
document.ontouchmove = function (e) {
  // Will prevent default action
  e.preventDefault();
};

// Case 2
document.ontouchmove = function () {
  // Will prevent default action
  return false;
};

// Case 3
document.addEventListener('touchmove', function (e) {
  // Will prevent default action
  e.preventDefault();
});

// Case 4
document.addEventListener('touchmove', function () {
  // WILL NOT prevent default action
  return false;
});
gulima
  • 139
  • 2
  • 11