Reputation: 28338
I'm working on a site which requires a lot of click events, but I can't for the love of coding figure out how to make it compatible with both desktops and touch devices.
Here is a typical click event, which uses both click
and touchend
to cover both desktop and touch devices:
$('#myBtn').on('click touchend', function(e) {
// Some code
});
The problem with this though is that it runs twice on touch devices, which is a huge problem. I've tried using touchstart
and separating with a comma ('click, touchend'
) as well but with no luck, also haven't been able to find a solution whilst searching the web.
Is this the way to make sure that your click events fire properly? If so, why isn't it working as expected? If not, what would be a more suitable way?
Upvotes: 1
Views: 48
Reputation: 167182
Use this way:
var eventH = "";
if ('ontouchstart' in document.documentElement)
eventH = "touchend";
else
eventH = "click";
// Just taking care of exceptions.
if (eventH != "")
$('#myBtn').on(eventH, function(e) {
// Some code
});
Upvotes: 2