Raduken Raduken - 6 months ago 18
Javascript Question

Remove the :hover event on mobile devices

I have the

:hover
event working on a website, but I have a problem when you use the system on mobile devices.

Is there a way to remove it in css or js? I have tried so many things but I have no luck.

I tried modernizr.com and media queries with no success.

my sass code:

ul {
li {
padding: 20px;
&:hover {
background-color: $red;
color: $black;
}
}
}


media query:

@media (max-width: $screen-sm-min) {
ul {
li {
&:hover {
color: inherit;
cursor: pointer;
}
}
}
}


sass mq variable:

$screen-sm-min: 768px;

Answer

You could use CSS media queries for interaction features but they are relatively new, iOS9 + and Android 5+: http://caniuse.com/css-media-interaction

You can use to only apply :hover styles where this feature is available

/* :hover will only work in Edge, Chrome, Safari 9+ for now  */
@media (hover: hover) {
    .your-selector:hover {
        color: red;
    }
}

Or, if you want broader support right now, only remove the :hover where possible:

/* :hover will be removed in iOS 9+ and Android 5+  */
.your-selector:hover {
    color: red;
}
@media (hover: none) {
    .your-selector:hover {
        color: oldcolor; 
    }
}

If you want even broader support, you need to detect touch capabilities via javascript. A fairly standard way to do it is this:

/* add a class to <html> */
var isTouch = 'ontouchstart' in window;
document.documentElement.className += isTouch?' touch ':' no-touch ';
/* only use hover when the no-touch class is present */
.no-touch {
    .your-selector:hover {
        color: red;
    }
}

Using this last solution with your code:

ul {
  li {
    padding: 20px;
     .no-touch &:hover {
      background-color: $red;
      color: $black;
    }
  }
}
Comments