iPhone vs Javascript event suppression

Tags: , , ,



I’ve got a simple click handler that does something on the screen instead of visiting that link. Here’s the code (I’m cutting out the nonsense but the important stuff is accurate):

<a href="#" id="others">Link Text</a>

<script type="text/javascript" src="./path/to/jquery.js"></script>
<script type="text/javascript">
$('#others').on('click', function(ev){
    ev.preventDefault();
    ev.stopPropagation();

    // Doing stuff (some simple DOM manipulation)

    return false;
});
</script>

This works fine on proper browsers. It works fine on Android (both older webkit and newer Chrome builds) and it works fine on iOS on the iPad 2… But one of my users is using an iPhone 4 and that’s where all the fun starts.

When they click the link, the link loads. Despite three separate triggers not to, the event is still firing. Other javascript is working on the page and as I say, this is working everywhere else. Actually to confuse things a little more, the event is suppressed very, very occasionally. Less than 1% of the time.

So is this a known issue with iPhones? Is there a better way of doing all this?

The javascript is loaded at the end of the body (still inside it, but after all the DOM elements it mentions). jQuery version is 1.10.1

Answer

try using href="javascript:void();"

<a href="javascript:void();" id="others">Link Text</a>

$('#others').on('click', function(ev){
//ev.preventDefault();
//ev.stopPropagation();

// Doing stuff (some simple DOM manipulation)

return false;
});


Source: stackoverflow