Usman Sikander
Usman Sikander

Reputation: 79

Does touch in a touch device get detected with the click event in all devices?

I have some jquery code that goes like this

$(this).click(function() {
    //code
});

I wondered if it would work in touch devices as well (respond to touch events the way it does to click events in laptops) so I tested it using touch simulation in Firefox developer tools and it did.

I thought maybe this is because all touch devices consider touch events as click events so I googled this and turns out my assumption was wrong because touch is a separate event in javascript. There are ontouchstart and ontouchend but they are not supported in some browsers. Though I still found code like this.

$(this).on("click touchstart",function() {
    //code
});

So why did it work with the touch simulation? Does it only work this way in some touch devices? And what can be my final sure solution to make my code work in all devices with both click and touch, whichever the browser?

Upvotes: 1

Views: 2400

Answers (1)

Asfan Shaikh
Asfan Shaikh

Reputation: 769

You can detect click and touchstart events separately by using this function.

var clickEvent = (function() {
  if ('ontouchstart' in document.documentElement === true)
    return 'touchstart';
  else
    return 'click';
})();

$(this).on(clickEvent,function() {
    //code
});

Upvotes: 3

Related Questions