Disabling the Context Menu on Long Taps on Android

Disabling the context menu on long taps on Android

This should work on 1.6 or later (if I recall correctly). I don't believe there's a workaround for 1.5 or earlier.

<!DOCTYPE html>
<html>
<head>
<script>
function absorbEvent_(event) {
var e = event || window.event;
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
e.cancelBubble = true;
e.returnValue = false;
return false;
}

function preventLongPressMenu(node) {
node.ontouchstart = absorbEvent_;
node.ontouchmove = absorbEvent_;
node.ontouchend = absorbEvent_;
node.ontouchcancel = absorbEvent_;
}

function init() {
preventLongPressMenu(document.getElementById('theimage'));
}
</script>
</head>
<body onload="init()">
<img id="theimage" src="http://www.google.com/logos/arthurboyd2010-hp.jpg" width="400">
</body>
</html>

Preventing default context menu on longpress / longclick in mobile Safari (iPad / iPhone)

Thanks to JDandChips for pointing me to the solution. It works perfectly in combination with the longclick plugin. For documentation sake I'll post my own answer to show what I did.

HTML:

<script type="text/javascript"
src="https://raw.github.com/pisi/Longclick/master/jquery.longclick-min.js"></script>

<p><a href="http://www.google.com/">Longclick me!</a></p>

The Javascript already was OK:

function longClickHandler(e){
e.preventDefault();
$("body").append("<p>You longclicked. Nice!</p>");
}

$("p a").longclick(250, longClickHandler);

The fix was to add these rules to the style sheet:

body { -webkit-touch-callout: none !important; }
a { -webkit-user-select: none !important; }

Disabled context menu example.

How to restrict default context menu on long press in android/ios devices and show custom menu?

It's the same as disabling right click - add this listener:

document.addEventListener('contextmenu', event => event.preventDefault());

Tested on Firefox for Android



Related Topics



Leave a reply



Submit