Explain Codes LogoExplain Codes Logo

Tooltips for mobile browsers

web-development
responsive-design
javascript
accessibility
Nikita BarsukovbyNikita Barsukov·Sep 26, 2024
TLDR

To create tooltips on mobile, leverage CSS pseudo-elements and touch events. Enable tooltips on touch using the :active pseudo-class in CSS instead of hover states:

<a href="#" title="Tooltip tooltip" ontouchstart="">Tap me!</a>
a:active:after { content: attr(title); position: absolute; // tooltip here, there and everywhere! }

This way, tapping the element displays the tooltip, similar to the hover effect on desktops.

Full-blown tooltip creation

Robust tooltips: going beyond title

Mobile devices and the title attribute aren’t best friends. For better accessibility, let's move to HTML data attributes and a sprinkle of JavaScript:

<button data-tooltip="This is a tooltip" onclick="showTooltip(this)"> Tap for info </button>
function showTooltip(element) { // Show me the tooltip, Watson! }

Tooltip positioning: clearing the view

In the mobile world, screen space is gold. So, ensure tooltips do not obstruct content. Use JavaScript to dynamically calculate the tooltip's position, based on the element's positioning:

function positionTooltip(element, tooltip) { // The art of perfect positioning }

User interactivity with touchscreens

For touch-friendly tooltips, swap :hover with ontouchstart events. Use JavaScript events like touchend to dictate when to show or hide tooltips. Especially for interactive elements, you may want to trap focus within the tooltip.

The art of crafting mobile tooltips

Embracing mobile variety with media queries

CSS media queries can create responsive tooltips, adjusting to diverse mobile screen sizes. This promotes usability across all devices.

@media (max-width: 600px) { // When small screens strike }

Javascript - the extra mile for mobile

JavaScript can add interactivity to tooltips. A toggle system can reveal tooltips on a tap and hide them a tap beyond their bounds:

function toggleTooltip(event) { // Now you see me, now you don't } document.addEventListener('touchstart', toggleTooltip);

Accessibility: Empowering every user

Remember, aria-describedby and ARIA attributes aid screen readers in identifying tooltips. Utilize focus management to ensure keyboard users do not miss the tooltips.

Rethink tooltips: modal intervention

For critical information, consider modals or pop-ups as an alternative. They are more mobile-friendly for detailed content presentation.

<div id="modal" role="dialog" aria-labelledby="modalTitle" aria-modal="true"> <!-- Content galore inside --> </div>