Vinzcent
Vinzcent

Reputation: 1448

Mobile Safari - event.target in touch event

I would like to have the target when a touch something on the screen of my iPad. But unfortunately it always returns the currentTarget, never the target.

document.addEventListener('touchstart', onDocumentTouchStart, false);

function onDocumentTouchStart(event) {

  if (event.target.tagName.toLowerCase() == "div" || event.target.tagName.toLowerCase() == "canvas") {
      // do someting
  }
  else
  {
     // do something else
  }

}

But event.target.tagName is always "HTML". But never the real element I touched, for example an anchor tag or a div.

How do I get the real element I touched?

Upvotes: 1

Views: 8462

Answers (1)

Luke Dennis
Luke Dennis

Reputation: 14550

You might try the "event.touches" array, which will have one entry for each finger currently down, with the "target" value referencing the DOM element touched.

function onDocumentTouchStart(event) {
    if (event.touches[0] && event.touches[0].target.tagName.toLowerCase() == "div") {
        // do someting
    }
}

However, I should note that I was unable to duplicate the original issue; when I tried it, event.target referred to the touched div as intended. You might also check your CSS and/or JS plugins that might be interfering with event bubbling.

Upvotes: 4

Related Questions