jqueryhoverjquery-hover

Hover event, but not on touch/mobile devices


I am trying to create a hover event that shows an image. On my desktop/laptop it fires correctly. However on a mobile (touch), the image only appears when the modal link is clicked, then it is sticky (it stays on screen).

On mobile or touch-screens, i don't want the hover event to fire.

Here is what i am working with.

Jsfiddle

HTML

<a href="#test" id="test-parent">Hover to show image</a>

<img class="preview" id="test-child" src="https://mayvers.com.au/wp-content/uploads/2017/09/test-image.jpg" />

<script>
  $("#test-parent").hover(function() {
    $("#test-child").fadeToggle();
  });
</script>

CSS

.preview {
  display: none;
  position: absolute;
  bottom: 0;
  right: 0;
  z-index: 1;
  height: 50%;
}

Solution

  • You can check if it is touch event or not and fire the hover effect accordingly.

    <script>
      $("#test-parent").hover(function() {
       if(!isTouchEvent()){
        $("#test-child").fadeToggle();
       }
      });
    
      function isTouchEvent() {
        return 'ontouchstart' in document.documentElement
               || navigator.maxTouchPoints > 0
               || navigator.msMaxTouchPoints > 0;
      }
    
    </script>
    

    JSFiddle Demo