raduken
raduken

Reputation: 2119

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;

Upvotes: 2

Views: 9041

Answers (1)

fregante
fregante

Reputation: 31708

You could use CSS media queries for interaction features: http://caniuse.com/css-media-interaction

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

@media (hover: hover) {
    .your-selector:hover {
        color: red;
    }
}

Alternatively, you can detect touch capabilities via javascript, but this is not advisable and generally not necessary since now you can just do it via CSS, dynamically.

/* 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;
    }
  }
}

Upvotes: 7

Related Questions