Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<a href onClick="return false;"> not working in Safari/iOS?

Tags:

html

ios

I have this code in my page:

<a href onClick="return false;">Press me!</a>

The link is placed inside a span with a useful onClick event.

Now, in Chrome and Firefox this works perfectly. The link is clicked, the useful event is executed and everybody's happy. In iOS (iPhone and iPad) using the default Safari browser, this fails miserably - after the link is clicked the whole page is reloaded and the useful event is never executed.

I also tried

<a href="#" onClick="return false;">Press me!</a>

Which I understood to be the wrong way of doing this. In Chrome and Firefox it works well, but in iOS' Safari it jumped back to the beginning of the page (but it DID execute the useful event, so in a sense it was better).

What am I missing?

like image 683
Gadi A Avatar asked Dec 20 '22 23:12

Gadi A


1 Answers

You can set href="#", and I'm noticing the same jumping to the top of the page. # is an in-page anchor, which I believe refers to the top of the page. I'm not clear on the defined behavior for that. But alas, you want to cancel it.

In the iPhone 5.0.1 Simulator, combining both cancelation methods works and doesn't scroll to the top. This is my complete test.html file. It works in the simulator, Chrome and OS X Safari.

<div style="height: 1000px; background-color: blue;"></div>
<a href="#" onClick="event.preventDefault(); return false;">Poke it!</a>
<div style="height: 1000px; background-color: red;"></div>

For the record, removing the event.preventDefault(); duplicates your bug.

like image 83
wjl Avatar answered Jan 10 '23 04:01

wjl