Disable jquery effects for touch screens

There was a recent question of Stack Overflow looking to disable mouse hover events in jQuery on touch devices. My first thought was why disable them on touch when you could just enable them when touch wasn’t available.

I have some jquery mouseover effects on my website that I need to disable for touch screens, however, how do I know what width of screen to disable the JQuery? At the moment I have it at less than 800px. This works on an ipad portrait but then when I turn it landscape the JQuery is activated again.
I have read that Ipad landscape width is 1024px but this could also be the size of a small none touch screen. Is there a way I can specify effects for certain devices instead of screen widths ?

A question from Stackoverflow

To achieve this you should look at working the other way and instead of disabling mouse over events for touch devices ADD the events for non-touch devices.

Add Modernizr to the project your working on (you’ve probably already got it in there). Once added you can include a test for “touch” by adding it as a class to the HTML element

<html class="touch"> 

If the device has touch capabilities then everything will remain as is, however if the device does not have touch then moderizr will covert that from touch to to no-touch

<html class="no-touch"> 

You can then bind your mouse events off the html element having the class of .no-touch

I’ve put an example of this in the code pen.

Code Pen Example of Exporter

See the Pen Modernizr test for touch by Justin Avery (@justincavery) on CodePen.

Some other options

This assumes that you’re still loading the jQuery library for all devices and deciding whether to load the mouse over functions based on touch devices. If you’re looking at conditionally loading jQuery itself then you should look at enquire.js to load in jQuery at a specified width.

If you want to keep jQuery for other functions on smaller devices but want to improve performance you could look at using using Zepto.js as a lightweight alternative.

Subscribe to our Newsletter

Add your email address and receive an email every Friday covering off everything worth knowing about building your websites responsively.