Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect whether a browser supports mouseover events?

Let's assume I have a web page which has some onmouseover javascript behaviour to drop down a menu (or something similar)

Obviously, this isn't going to work on a touch device like the iPad or smartphones.

How can I detect whether the browser supports hover events like onmouseover or onmouseout and the :hover pseudotag in CSS?

Note: I know that if I'm concerned about this I should write it a different way, but I'm curious as to whether detection can be done.

Edit: When I say, "supports hover events", I really mean, "does the browser have a meaningful representation of hover events". If the hardware supports it but the software doesn't (or vice versa), there's no meaningful representation. With the exception of some upcoming tech, I don't think any touch devices have a meaningful representation of a hover event.

like image 991
Damovisa Avatar asked Jan 10 '11 03:01

Damovisa


People also ask

When the mouse over event is detected?

The mouseover event is fired at an Element when a pointing device (such as a mouse or trackpad) is used to move the cursor onto the element or one of its child elements.

How do you know if an element is hovered?

You can simply use the CSS :hover pseudo-class selector in combination with the jQuery mousemove() to check whether the mouse is over an element or not in jQuery. The jQuery code in the following example will display a hint message on the web page when you place or remove the mouse pointer over the DIV element's box.

How does mouseover event work?

The mouseover event occurs when a mouse pointer comes over an element, and mouseout – when it leaves. These events are special, because they have property relatedTarget . This property complements target . When a mouse leaves one element for another, one of them becomes target , and the other one – relatedTarget .


2 Answers

This method catches more devices/browsers

try {
   document.createEvent("TouchEvent");
   alert(true);
}
catch (e) {
   alert(false);
}

Read more

like image 79
Johan Avatar answered Sep 19 '22 08:09

Johan


var supportsTouch = (typeof Touch == "object");

Just detect if it's a touch device and then do your special stuff. This is the simplest approach since most touch devices emulate mouse events but no mouse driven device emulates touch events.

Update: Considering how many devices there are now a days and Johan's comments I'd recommend simply using Modernizr.

like image 33
Thomas Avatar answered Sep 19 '22 08:09

Thomas