1

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?

12
  • What fails when you only use "click"? Commented Oct 13, 2015 at 10:08
  • 1
    Missing ), I'd suggest to use something like this, var event = 'click'; if (touchDeviceSupportingTouchend) { event = 'touchend'; } $('selector').on(event, function() ... Commented Oct 13, 2015 at 10:09
  • @spender The function doesn't get run if using only click on touch devices. Commented Oct 13, 2015 at 10:11
  • Click should work fine on both Commented Oct 13, 2015 at 10:11
  • @DexTer I've ran multiple tests which shows that it doesn't :/ Commented Oct 13, 2015 at 10:12

1 Answer 1

2

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
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.