Using mousemove and touchstart to Detect Touch Devices
So you know I love hovers. I was recently trying to implement a hover that has the image as the link, and on hover the text of the link appears. The information that is hidden and shown on hover is vital to understanding what the link is and where it goes. Something that without knowing, a user might never want to click on the link. This hover/focus interaction works perfectly fine for keyboard and mouse users, but what about touch?
With touchable desktops coming out and tablets the size of tvs, using media queries with max-device-width isn’t as reliable as it used to be to show the hidden information by default for “mobile sized” devices. This led me to a few different searches for a new solution.
Josh Clark wrote about it the dilemma here: http://globalmoxie.com/blog/desktop-touch-design.shtml and talks and about how we have to design our UIs for touch. Great points, but going back to design wasn’t an option here.
I looked into Modernizr, but there are a slew of issues opened right now (such as https://github.com/Modernizr/Modernizr/issues/548) that investigate how to make touch event detection more reliable without setting off false positives.
In this case, false positives using Modernizr wouldn’t be the worst thing in the world, as that falls back to the Josh Clark approach of designing for touch first. But we tried something else anyway..
Mark Huot and I opened up Codepen and decided to try out a few different tests around using the mousemove function. We figured, hey if there’s a mouse movement, it’s not touch right? This kinda worked, but we quickly found out that clicking on links on our iPad or clicking anywhere on our Android fired off the mousemove function. So that didn’t work. We ended up with a few different functions, until we finally reached this: http://codepen.io/Jenn/full/ALHEf
We style for touch first by default, so the product information shows. Then after the mousemove function fires, a class is applied of ‘hover-on’. With this class we adjust the styles appropriately to set the hover opacity to 0 and then to 1 on hover. Touch devices should never get that class, and therefore, always show the information.
When touchstart occurs and someone clicks on a touch device, it unbinds the function and never receives the class.
The down side, when you first load the page, until you mouse within the document you will see the information and then it will hide once you mouse anywhere. Adding a transition on the opacity will at least ease this so it’s not so jarring. Maybe you might even like it as an indicator to your users that there is more info???
This relies on touchstart running before mousemove, which in our limited tests it has. Please let us know what you find if you can test it out! Thanks!
Check out this Pen!
