George Mauer
George Mauer

Reputation: 122112

Reliably detect if a user is using a mouse on a webpage?

On our page we have some iframes in a long horizontally-scrolling <div>. If the user is using a mouse they can scroll with the scrollbars and we would like them to be able to select text within the iframes. If they are using touch only however, the scrollbars are a hassle and I would like to overlay a transparent element over the whole thing to give them the ability to scroll easily by dragging, this of course sacrifices the select-text feature but makes sense in that scenario.

Which gets me to my question, is there a way to reliably detect if a user is interacting with a webpage via a mouse?

Everything I've seen on detecting touch or mouse is that touch will broadcast mouse events so it is very difficult to detect touch OR mouse (not to mention that you can have both). My problem is simpler - it is whether the user has interacted with the page via a mouse.

Can anyone think of a way to check this reliably?

Upvotes: 2

Views: 595

Answers (1)

Niels Keurentjes
Niels Keurentjes

Reputation: 41958

A mouse can do one single thing a touch device can never do - move without having any buttons pressed. So I'd just install an onMouseMove event on page load, and if it triggers without buttons pressed mark the user as a mouse user. You could then persist this through a cookie or LocalStorage since the flag will not change within the same environment, and remove the event right away. The precise way of implementing the single-fire event depends on which library you use (if any at all), but it should be easy with Mootools/JQuery docs in hand.

In general I'd recommend the easier route of just checking for a touch interface in most cases :

if('ontouchstart'in window) 
{
    /* it's a touch device */ 
}

Upvotes: 3

Related Questions