How do I simulate a hover with a touch in touch enabled browsers?
Creatively imitate hover effects for touchscreens by toggling a CSS class using JavaScript on touchstart
and touchend
events. For a speedy usage:
Apply the appropriate styles by matching the JavaScript with a CSS class:
Bind .simulated-hover
class to the desired HTML elements to cheat hover on touch. This ensures a hover-flavored visual feedback for touchscreen fans!
Deep Dive: How it works?
Before diving deep, let's have a brief background. Hover effects occur when a cursor hovers over an element without activating it. But touchscreens, they don't do hovering. They are all about active interactions. Hence, to fake a pseudo-hover state, we need to juggle a bit with CSS and JavaScript.
Using Touch Events in jQuery
With jQuery, we efficiently bind touch events to elements to swing classes around:
Here, we clean up by removing the 'on-hover' class when the finger moves away or lifts off, ensuring a smooth user experience.
Saying 'No' to Unwanted Select and Highlights
Styling is not just about shininess. It's also about taking care of undesired glimmers, like text selection or tap highlights:
Hover + Touch = Unification
We are inclusive. So why leave out non-touch devices? Let's unite them!
mouseenter
and mouseleave
now shake hands with touchstart
and touchend
ensuring a smooth hover dance across all devices.
Don't Forget Long Press Context Menu
We designers also need to be aware of long presses triggering Context Menu. Plan accordingly while designing touch interactions to avoid unintended results:
This ensure hover effects occur only when the users indicates through a long press, creating a more engaging interaction.
Building Robust Hover Simulation
Time to Consider: Trigger Without Hover
On mobile devices, consider executing AJAX calls directly on touch events, bypassing the need for a hover event:
This method is recommended for actions where a hover state doesn't uniquely contribute to the user experience or the element's functionality.
A Better Match: Hover and Active States
In some scenarios, it's not about ':hover'. Instead, wisely use the ':active' pseudo-class, which suits elements like buttons:
Engaging Interactions with Long Touch Triggers
Creating more engaging interactions by implementing a long touch trigger for hover effects is an excellent strategy especially with elements with hover-only options (like tooltips):
This helps in creating a well-defined and purposeful activation of a hover state, imitating the careful hover of a mouse pointer.
Was this article helpful?