Categories
JavaScript Answers

How to simulate a hover with a touch in touch enabled browsers with JavaScript?

Spread the love

Sometimes, we want to simulate a hover with a touch in touch enabled browsers with JavaScript.

In this article, we’ll look at how to simulate a hover with a touch in touch enabled browsers with JavaScript.

How to simulate a hover with a touch in touch enabled browsers with JavaScript?

To simulate a hover with a touch in touch enabled browsers with JavaScript, we add a touchstart event listener and some styles.

For instance, we write

document.addEventListener("touchstart", () => {}, true);

to add a touchstart event listener to document.

Then we write

element:hover,
element:active {
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  -webkit-user-select: none;
  -webkit-touch-callout: none;
}

to set the touch highlight color with

-webkit-tap-highlight-color: rgba(0, 0, 0, 0);

And we disable context menu on long press on the element with

-webkit-touch-callout: none

Conclusion

To simulate a hover with a touch in touch enabled browsers with JavaScript, we add a touchstart event listener and some styles.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *