10

Can anyone please explain to me why this is working in the browser but not on mobile devices like Apple's iPhone. On iPhone, I never get the hello from the alert. Why?

<div class="close">
  Click here
</div>

JS:

$(document).on('click', '.close', function() {
  alert('hello');
});

Example here: https://jsfiddle.net/27ezjrqr/5/

Andhi Irawan
  • 456
  • 8
  • 15
caramba
  • 21,963
  • 19
  • 86
  • 127

4 Answers4

41

By default, divs are not a "clickable" elements. But adding cursor: pointer; makes iOS treat it as clickable.

So all you need to do is add

.close {
    cursor: pointer;
}

to your CSS and then it will work.

Proof here: https://jsfiddle.net/27ezjrqr/6/

$(document).on('click', '.close', function() {
  alert('hello');
});
.close {
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="close">
  Click here
</div>
Gavin
  • 2,123
  • 1
  • 15
  • 19
  • I don't believe it, but you are correct! Thank you, that does work indeed! – caramba Mar 11 '16 at 17:24
  • Well I would still like to know why this strange behaviour is. So I'll wait a bit and accept sooner or later if no other answer will occur... – caramba Mar 11 '16 at 17:25
  • As far as I understand it, by default, divs are not a "clickable" element so iOS doesn't treat them as such. Adding the cursor / pointer makes them a clickable item. – Gavin Mar 11 '16 at 17:33
  • thank you for the update! Now this is so easy to understand and considered it this way it does make sense! Tahnk you – caramba Mar 11 '16 at 18:30
  • 1
    this is great, you saved our two days of efforts with this. – Shivananda Chary Oct 17 '18 at 09:57
1

I used the touchstart event with the click , it did the job for me

 $(document).on("click touchstart tap", "#button_X", function (){
//your code here      
 });
  • You say the same as @dannyjolie almost 2 years ago: https://stackoverflow.com/questions/35945970/jquery-on-click-not-working-on-iphone/35946223#35946223 . Also be careful with using `touchstart and tap` as the function then could fire twice ... – caramba Nov 21 '17 at 07:56
  • Also be careful using touchstart as it will fire even if user is scrolling (as opposed to intentionally clicking). – Lauren Dec 28 '17 at 21:55
0

The Javascript alert() and more bugs are fixed as of iOS 7.0.3.

acardoso
  • 68
  • 5
  • Hi acardoso, thank you for your answer. Why does this https://jsfiddle.net/vvsq2gw1/ work on iPhone and the example in the question does not? – caramba Mar 11 '16 at 17:16
  • I am guessing there is something to do with the click event. – acardoso Mar 11 '16 at 17:25
0

Click events don't work like expected on iOS. You can use something like touchstart instead, or use a weird iOS quirk: in your CSS, set .close{cursor:pointer}.

dannyjolie
  • 10,959
  • 3
  • 33
  • 28