How can I react when a user touches an HTML element on an iPhone?

I am displaying some HTML content in my iPhone application using UIWebView. I have a link to the image, and I want it to change when the user touches it - at the moment when the user puts his finger on the screen, and does not wait for them to pull their finger.

What CSS or JavaScript concept can I implement? I looked at the hover and active states in CSS, but they don't seem to be what I need: hover refers to touch, not touch, and active seems to have no effect.

+4
source share
2 answers

You can try this.

I think this should be what you are looking for!

http://articles.sitepoint.com/article/iphone-development-12-tips/2

8: Touch events

Of course you use your iPhone with a finger instead of a mouse; rather than clicking, you tap. Moreover, you can use several fingers to touch and tap. On iPhone, mouse events are replaced by touch events. It:

  • touchstart
  • touchend
  • touchmove
  • touchcancel (when the system cancels the touch)

When you subscribe to any of these events, your event listener will receive an event object. The event object has some important properties, for example:

  • touches - a set of touch objects, one for each finger that touches the screen. Touch objects such as pageX and pageY properties containing the touch coordinates on the page.
  • targetTouches - works like a touch, but only registers the touch of the target element as opposed to the whole page.

The following example is a simple drag and drop implementation. Let's put the box on a blank page and drag it around. All you have to do is subscribe to the touchmove event and update the position of the window as the finger moves, for example:

 window.addEventListener('load', function() { var b = document.getElementById('box'), xbox = b.offsetWidth / 2, // half the box width ybox = b.offsetHeight / 2, // half the box height bstyle = b.style; // cached access to the style object b.addEventListener('touchmove', function(event) { event.preventDefault(); // the default behaviour is scrolling bstyle.left = event.targetTouches[0].pageX - xbox + 'px'; bstyle.top = event.targetTouches[0].pageY - ybox + 'px'; }, false); }, false); 

The touchmove event touchmove first cancels the default finger behavior, otherwise Safari will scroll the page. The event.targetTouches collection contains a list of data for each finger currently on the target div.
We only care about one finger, so we use event.targetTouches[0] . Then pageX gives us the X coordinate of the finger. From this value, we subtract half the width of the div so that the finger remains in the center of the field.

Hope this helps!

+5
source

Try Javascript "onMouseDown", hope mobile Safari fires this event.

 <a href="#any_URL" onMouseDown="callSomeFunction();return true;">Link</a> 
+3
source

All Articles