Joel Z. Joel Z. - 11 days ago 6
jQuery Question

jQuery on() doesn't work with mobile Safari

I want to toggleClass of lists dynamically generated with jQuery $.ajax({...}) with an XML file. It works fine on the desktop with Safari and Chrome but not with mobile Safari. Delegate and Live don't work on mobile either.

I'm using jQuery 1.7.2 iPad (iOS 5.1) iPhone (iOS 5.0.1)

Not using jQuery mobile

jQuery docs recommends using .on() instead of .live() since live is deprecated starting 1.7

oringal html

<ul id="movies">
/* empty */
</ul>


after dynamic build

<ul id="movies">
<li>Movie-1</li>
<li>Movie-2</li>
<li>Movie-3</li>
</ul>


The following works on desktop Safari and Chrome but not on mobile Safari.

$(document).on('click', '#movies li', function() {
$(this).toggleClass('selected');
});


cyrusv seems to have asked a similar question and answered the solution himself too but he didn't elaborate enough.
http://stackoverflow.com/a/9538134/372567
Says:


add onclick='' to the div element. Not sure why
that worked, but it did. –

Answer

It isn't best practice to bind events to the document element, you should do this instead:

$('#movies').on('click', 'li', function() {
    $(this).toggleClass('selected');
});