Explain Codes LogoExplain Codes Logo

How do I simulate a hover with a touch in touch enabled browsers?

web-development
responsive-design
promises
callbacks
Nikita BarsukovbyNikita Barsukov·Oct 28, 2024
TLDR

Creatively imitate hover effects for touchscreens by toggling a CSS class using JavaScript on touchstart and touchend events. For a speedy usage:

//Saving the world with a touch...or two! document.querySelectorAll('.simulated-hover').forEach(item => { item.addEventListener('touchstart', () => item.classList.add('on-hover')); item.addEventListener('touchend', () => item.classList.remove('on-hover')); });

Apply the appropriate styles by matching the JavaScript with a CSS class:

.on-hover, .simulated-hover:hover { /* Your awesome hover styles go here */ }

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:

//With great power(i.e., jQuery) comes great responsibility(to use it)! $('.simulated-hover').on('touchstart', function() { $(this).addClass('on-hover'); //Gotcha! }).on('touchend touchmove', function() { $(this).removeClass('on-hover'); //Ops! Not anymore! });

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:

.simulated-hover { -webkit-user-select: none; // "No touching!" - the text -webkit-tap-highlight-color: transparent; // Now you see me (No, you don't!) }

Hover + Touch = Unification

We are inclusive. So why leave out non-touch devices? Let's unite them!

function toggleHoverState(event) { // Let's play hide and seek with hover state! event.target.classList.toggle('on-hover'); } document.querySelectorAll('.simulated-hover').forEach(item => { item.addEventListener('mouseenter', toggleHoverState); // Come, you are invited! item.addEventListener('mouseleave', toggleHoverState); // Goodbye, see you next time! item.addEventListener('touchstart', toggleHoverState); item.addEventListener('touchend', toggleHoverState); });

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:

const LONG_TOUCH_DURATION = 500; // Long time no C! $('.simulated-hover').on('touchstart', function(event) { this.timeout = setTimeout(() => { $(this).addClass('on-hover'); // Class-ified }, LONG_TOUCH_DURATION); }).on('touchend touchmove', function(event) { clearTimeout(this.timeout); $(this).removeClass('on-hover'); // Class-dismissed! });

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:

$('.interactive-element').on('click', function() { // No time for hover, let's AJAX it up! loadData(this.dataset.url); });

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:

.simulated-hover:active { /* Welcoming hover styles with open arms */ }

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):

let touchTimer; $('.simulated-hover').on('touchstart', function() { touchTimer = setTimeout(function() { // Hover code engaged! }, 800); // The longer, the hover-er! }).on('touchend touchcancel touchmove', function() { clearTimeout(touchTimer); // Let's move on from hover });

This helps in creating a well-defined and purposeful activation of a hover state, imitating the careful hover of a mouse pointer.