Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use jQuery for click event in iPhone web application

When I use jQuery for a simple click event it only works for links. Is there a way to make it work for spans etc:

$("span.clicked").live("click", function(e){alert("span clicked!")});  $("a.clicked").live("click", function(e){alert("link clicked!")}); 

The SPAN works in Safari but not Mobile Safari (on iPhone or iPad) whereas the A tag works in both.

like image 258
Gazzer Avatar asked Jun 11 '10 18:06

Gazzer


People also ask

How can use click event in jQuery?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.

What is jQuery click event?

jQuery click() Method The click event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click event occurs.

How click event works in Javascript?

An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.


2 Answers

I struggled with this as well. After lots of toying around and trying to figure out the problem, I came across a simple solution.

If you set the element's cursor to pointer, it magically works again with Jquery's live and the click event. This can just be set globally in the CSS.

like image 79
Plynx Avatar answered Sep 20 '22 22:09

Plynx


You need to listen for the "touchstart" and "touchend" events. Add the listeners with jQuery...

$('span').bind( "touchstart", function(e){alert('Span Clicked!')} ); 

You may wish to listen for a touchstart and touchend so that you can verify that the element targeted when the finger touched is the same as the element targeted when the finger was removed.

I'm sure there is probably a better way to do it but that should work :)

Edit: There is a better way! See https://stackoverflow.com/a/4910962/16940

like image 32
Sam Avatar answered Sep 20 '22 22:09

Sam