Hover event, but not on touch/mobile devices

Hi All,

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%;
}

You would need to detect touchstart and touchend I think and give that to touch devices and the hover to non touch devices.

e.g.

<script>
  if ("ontouchstart" in document.documentElement) {
    $("#test-parent").on({
      'touchstart': function(e) {
        $("#test-child").fadeIn();
		e.preventDefault();
      }
    });
    $("#test-parent").on({
      'touchend': function(e) {
        $("#test-child").fadeOut();
		e.preventDefault();
      }
    });
  } else {
    $("#test-parent").hover(function() {
      $("#test-child").fadeToggle();
    });
  }  
</script>

That code could probably be tidied up a lot by the js gurus here but should do what you want although I believe there could be issues in imitating hover for devices that don’t really hover. :slight_smile:

You don’t really need js to do hover on desktop anyway as you can use css with a transition to hide and show elements.

Also note that the position absolute on the image is relative to the body and should the body scroll then so will the image but I’m guessing you just showed a snippet of the real application.:wink:

I may have misread your request as it seems you don’t want anything to happen on a touch device and in that case you can just give the hover event to non touch devices.

<script>
  if (!("ontouchstart" in document.documentElement)) {
      $("#test-parent").hover(function() {
       $("#test-child").fadeToggle();
    });
   } 
</script>

Bear in mind some desktops are touch and hover so the above answers may not be foolproof.

2 Likes

yes perfect! thanks for such a comprehesive reply

1 Like