Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For a website I want to show a custom context menu when a user "longpresses" the screen. I've created a jQuery Longclick listener in my code to show a custom context menu. The context menu is displayed, but the iPad's default context menu is also displayed! I tried to prevent this by adding a preventDefault() to the event in my listener, but this does not work:

function showContextMenu(e){   e.preventDefault();   // code to show custom context menu }  $("#myId").click(500, showContextMenu); 

Questions

  1. Can you prevent the iPad's default context menu to show?
  2. Can it by done using the jQuery Longclick plugin?

The Longclick plugin has some specific handling for the iPad (assuming by this snippet of it's source code):

if (!(/iphone|ipad|ipod/i).test(navigator.userAgent)){   $(this)   .bind(_mousedown_, schedule)   .bind([_mousemove_, _mouseup_, _mouseout_, _contextmenu_].join(' '), annul)   .bind(_click_, click) } 

So I assume this answers my second question (assuming the plugin used the correct event).

like image 737
Jasper de Vries Avatar asked Sep 06 '12 16:09

Jasper de Vries


People also ask

What is long press on Iphone?

Long-press (also known as press-and-hold) gestures detect one or more fingers (or a stylus) touching the screen for an extended period of time. You configure the minimum duration required to recognize the press and the number of times the fingers must be touching the screen.


2 Answers

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.

like image 73
Jasper de Vries Avatar answered Oct 14 '22 15:10

Jasper de Vries


<style type="text/css"> *:not(input):not(textarea) {   -webkit-user-select: none; /* disable selection/Copy of UIWebView */   -webkit-touch-callout: none; /* disable the IOS popup when long-press on a link */ }        </style> 

If you want disable only anchor button tag use this:

a {   -webkit-user-select: none; /* disable selection/Copy of UIWebView */   -webkit-touch-callout: none; /* disable the IOS popup when long-press on a link */ } 
like image 35
Narsingh Tomar Avatar answered Oct 14 '22 16:10

Narsingh Tomar