Disable taphold default event, cross device

3.1k views Asked by At

I'm struggling to disable default taphold browser event. Nothing that I have found on Google provided any help. I have only Android 4.4.4 mobile and Chrome dev tools for testing. I tried CSS fixes, such as webkit-touch-callout and others, but apparently they don't work for Android, also they don't work in Chrome dev tools. I also tried detecting right click, (e.button==2), it doesn't work.

I came up with a solution, but it solves one problem and creates another. I just want to have a custom action for 'long press' event for selected anchors and I don't want the default pop up to appear (open in a new tab, copy link address, etc.) This is what I did:

var timer;
var tap;

$("body").on("touchstart", my_selector, function(e) {
    e.preventDefault();
    timer = setTimeout(function() {
        alert('taphold!');
        tap=false;
    },500);
});

$("body").on("touchend", my_selector, function() {
    if(tap) alert('tap');
    else tap=true;
    clearTimeout(timer);
});

It successfully disables the default taphold event and context menu doesn't appear. However it also disables useful events, such as swipe. The links are in a vertical menu and the menu is higher than the screen, so a user has to scroll it. If he tries to scroll, starting on an anchor, it won't scroll, it will alert 'tap!'

Any ideas how could I disable taphold default or how could I fix this code so it disables only tap events and leave default swipe events enabled?

Edit: Now I thought about setting a timeout, if the pointer is in the same place for lets say 100ms, then prevent default action. However e.preventDefault(); doesn't work inside setTimeout callback.

So now I'm just asking about the simplest example. Can I prevent default actions after certain amount of time has passed (while the touch is still there).

And this is my whole problem in a fiddle. http://jsfiddle.net/56Szw/593/ This is not my code, I got this from http://www.gianlucaguarini.com/blog/detecting-the-tap-event-on-a-mobile-touch-device-using-javascript/

Notice that while swiping the box up and down, scrolling doesn't work.

2

There are 2 answers

0
Maciej Kravchyk On BEST ANSWER

I got the solution. It was so simple! I had no idea there's an oncontextmenu event. This solves everything:

$("body").on("contextmenu", my_selector, function() { return false; });
1
DarthVanger On

For an <img> I had to use event.preventDefault() instead of return false.

document.querySelector('img').addEventListener('contextmenu', (event) => {
  event.preventDefault();
}