views:

612

answers:

2

I have some css menus on my site that expand with :hover (without js)

This works in a semi-broken way on iDevices, for example a tap will activate the :hover rule and expand the menu, but then tapping elsewhere doesn't remove the :hover. Also if there is a link inside the element that is :hover'ed, you have to tap twice to activate the link (first tap triggers :hover, second tap triggers link).

I've been able to make things work nicely on iphone by binding the touchstart event.

The problem is that sometimes mobile safari still chooses to trigger the :hover rule from the css instead of my touchstart events!

I know this is the problem because when I disable all the :hover rules manually in the css, mobile safari works great (but regular browsers obviously don't anymore).

Is there a way to dynamically "cancel" :hover rules for certain elements when the user is on mobile safari?

I'm using jQuery.

A: 

A work around would be to detect the type of device the user is using, using the User-Agent header sent by the browser. Then based off this you could generate a dynamic style sheet, or point to a different style sheet from your HTML files, which ever suits you best.

The user agents you want to be looking for are something like:

Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10

Or

Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A566a Safari/419.3

But there are variations of these two, so you might want to just check if the strings "iPad" or "iPhone" exsist within whatever user agent is being sent.

Sam152
A better way to do this would be to simply check if the browser supports `touchstart`. But the problem again is that you can't cancel the `:hover` rules in the mobile.css.I've thought of doing `<body class="non-mobile">` by default but I consider that a ridiculous solution.
Christopher Camps
A: 

heres the code you'll want to place it in

// a function to parse the user agent string; useful for 
// detecting lots of browsers, not just the iPad.
function checkUserAgent(vs) {
    var pattern = new RegExp(vs, 'i');
    return !!pattern.test(navigator.userAgent);
}
if ( checkUserAgent('iPad') ) {
    // iPad specific stuff here
}
Luke