Skip to content

Instantly share code, notes, and snippets.

@rcmachado
Created November 4, 2013 14:21
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save rcmachado/7303143 to your computer and use it in GitHub Desktop.
Save rcmachado/7303143 to your computer and use it in GitHub Desktop.
Remove CSS :hover rules for touch devices to avoid iOS double-tap behavior. Copied and adapted from http://retrogamecrunch.com/tmp/hover (just a fix for sheet.cssRules)
// disable :hover on touch devices
// based on https://gist.github.com/4404503
// via https://twitter.com/javan/status/284873379062890496
// + https://twitter.com/pennig/status/285790598642946048
// re http://retrogamecrunch.com/tmp/hover
// NOTE: we should use .no-touch class on CSS
// instead of relying on this JS code
function removeHoverCSSRule() {
if ('createTouch' in document) {
try {
var ignore = /:hover/;
for (var i = 0; i < document.styleSheets.length; i++) {
var sheet = document.styleSheets[i];
if (!sheet.cssRules) {
continue;
}
for (var j = sheet.cssRules.length - 1; j >= 0; j--) {
var rule = sheet.cssRules[j];
if (rule.type === CSSRule.STYLE_RULE && ignore.test(rule.selectorText)) {
sheet.deleteRule(j);
}
}
}
}
catch(e) {
}
}
}
@dannycochran
Copy link

nice solution. one problem is that if you have a hover state that is the same as another class, you will lose the styling when that class is applied. e.g:

&:hover, &.active {
some:style
}

if the applied element has the active class, the rule will have been deleted.

@luicaps
Copy link

luicaps commented Jun 21, 2016

I tried using this code, and at first it worked. But when I create a production version (minifying the whole code), it somehow removes almost all CSS classes (including the layout bootstrap).

Copy link

ghost commented Feb 3, 2017

Luicaps,
Try RegExp(':hover') instead /:hover/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment