Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .on() and .delegate() doesn't work on iPad

If you try this snippet on desktop, everything works.
Whenever you try it on iPad, it won't do anything.

$('body').on('click', '#click', function() {      alert("This alert won't work on iPad");  });
div {     font-size: 24px;   }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div id="click">Click here</div>

Simple .click() handler works, but it isn't what I want. The same applies for .delegate(); and .live()

Is it a bug or something?

like image 719
Martin. Avatar asked Apr 15 '12 19:04

Martin.


2 Answers

It's a Safari mobile bug/feature : click events won't bubble all the way up to body.

Adding onclick="" is a known workaround, but IMHO it's easier to attach your listener on a first child of <body>.

See: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html

like image 78
mddw Avatar answered Oct 08 '22 13:10

mddw


Change the cursor style of the body on iOS to "pointer" and everything will work perfectly. You won't have to add onclick="" on every element you want clickable...

<script type="text/javascript">     $(function() {         // The trick         if (/ip(hone|od)|ipad/i.test(navigator.userAgent)) {            $("body").css ("cursor", "pointer");         }         // The test         $("body").on("click", "#click", function() {             alert("This also works on iOS !");         });     }); </script> <div id="click">Click here</div> 

I know what you're thinking right now: "WTF!".

like image 26
Boroboro Avatar answered Oct 08 '22 13:10

Boroboro