Learn how to fix IPad or iPhone Javascript/Jquery click problems

by Amir Sadeghian Posted on | Web Development

Today I was working on a project that was using Jquery. In this project, I was using Jquery click listener. Everything was working fine on Firefox and Chrome. However, when I tapped on the element on my Ipad the click event didn’t get fired. In this post, I will present an example of the problem and explain how to resolve it.

Problem

Let’s assume following is my HTML element and Javascript(JQuery).

<div class="slide">
	<img src="..." />
</div>
$(document).ready(function(){
	$('.slide').click(function(){
		$('body').css('background-color','red');
	});
});

Above Javascript in combination with the HTML will change the background color of the body of the page to red on click on the element with slide class. However this only works on Chrome and Firefox browsers and it doesn’t work on Safari Mobile. The cause of this problem is due to a known bug in Safari Mobile version 7 and higher. Due to this bug, the click event is not being fired on non-interactive elements. For example “Div” is a none interactive element. However “a” is an interactive element.

Solution

There are a few ways to fix this problem:

  • Avoid using non-interactive elements where you want to attach click listeners. Replace div, span with anchor element.
  • Use CSS to set pointer attribute of target element to pointer. In my case, I had to keep the div element. Therefore, I used the following solution to fix this problem:
    .slide{
    	cursor: pointer;
    }
    

Reference

https://developer.mozilla.org/en-US/docs/Web/Events/click#Safari_Mobile