"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Detailed explanation and application of Long Hover skills

Detailed explanation and application of Long Hover skills

Posted on 2025-04-16
Browse:290

Long Hover

Recently, I encountered a rather embarrassing CSS oversight. I was developing a website with a narrow sidebar containing icons. Lacking space for descriptive text, the design called for accessible, yet initially hidden, tooltips triggered by a prolonged hover. The tooltip would appear after a three-second hover.

My initial approach involved JavaScript state management:

  1. A state variable to track tooltip visibility (visible/hidden). This state would update a class on the relevant HTML element.
  2. Event listeners (mouseenter, mouseleave) to manage the state transitions.
  3. A three-second delay before setting the state to visible on mouseenter.
  4. The tooltip would remain hidden (mouseleave).

This was a React project, so using JavaScript state felt natural. However, in retrospect, it proved unnecessarily complex. The mouseenter and mouseleave events felt slightly unreliable, and the entire functionality could have been implemented more concisely and efficiently with CSS alone.

The embarrassing realization: I unnecessarily leveraged a JavaScript library when a CSS solution was readily available.

I retained the React UI but removed the JavaScript state management. The solution involved a simple CSS transition-delay property:

.thing {
  transition: 0.2s;
}
.thing:hover {
  transition-delay: 3s; /* delay hover animation only ON, not OFF */
}

This elegant one-liner perfectly achieves the desired long-hover effect.

This approach, however, doesn't fully address touch screen accessibility. While screen readers handle the accessible text and desktop users benefit from the tooltips, touch-only users might miss the icon labels. My project targeted large screens, assuming cursor availability, but touch accessibility remains a concern. If the element is a link, the :hover might activate on the initial tap. If the link leads to a page with a clear title, that might provide sufficient context. Otherwise, JavaScript event handling for touch events remains a viable option.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3