Jeff Demos
Jeff Demos

Reputation: 3

Jquery add classes and data on touchscreens

I'm not entirely sure if I understand how to detect touchscreens and change classes with Jquery. So anyway, I have a bootstrap nav menu with dropdowns that display on 'hover' on desktops. I have managed to disable the hover functions on touch devices using:

if (!("ontouchstart" in document.documentElement)) {
document.documentElement.className += " no-touch"; }

Now I want to add back in the classes in the dropdown items that enable the toggle dropdown again. This is what I came up with:

$('.dropdown a').on('touchstart', function(){
$(this).addClass('dropdown-toggle');
$(this).data('toggle','dropdown');
});

Apparently it's working on ipad, but not on my kindle fire. Why would the first code above work, but the 2nd one here not?

Upvotes: 0

Views: 150

Answers (1)

Dave Carney
Dave Carney

Reputation: 47

'ontouchstart' is Apples way of handling touch events, so iOS only.

For all other devices you have to use 'onpointerdown'.

Eloquently addressed here, http://www.stucox.com/blog/you-cant-detect-a-touchscreen/ a browser cannot truly detect if a touch capable display is present, so you have to assume all devices have touch capability and code appropriately.

To make it more complicated, trying to separate touch from click, goes out the window with a touchscreen laptop.

I wrote jQuery plugin that unifies touch/hover/click behavior for all devices that works exactly how you are approaching this. By swapping classes depending on what you are trying to do.

This article goes into more detail regarding how the browser is interpreting these different interactions. http://fallingmonocle.com/monocle-toggle.php

Upvotes: 1

Related Questions