Home >Web Front-end >CSS Tutorial >How to Create a Dynamic Tooltip with Fade-in/Fade-out Effects for a Div Element?

How to Create a Dynamic Tooltip with Fade-in/Fade-out Effects for a Div Element?

Linda Hamilton
Linda HamiltonOriginal
2024-12-18 18:30:17663browse

How to Create a Dynamic Tooltip with Fade-in/Fade-out Effects for a Div Element?

Add a Dynamic Tooltip to a div Element

Question:

Consider a div element with a label and an input field:

<div>
  <label>Name</label>
  <input type="text"/>
</div>

How do you create a tooltip that appears when users hover over the div element, with a subtle fade-in/fade-out effect?

Answer:

For basic tooltips that display a static message, you can utilize the title attribute:

<div title="This is my tooltip">

However, for tooltips with dynamic text and animated fade effects, a more advanced approach is required:

  1. Create a CSS animation for the tooltip.
  2. Add a JS event listener to handle the hover events.
  3. Create a tooltip DOM element and position it relative to the div.
  4. Add/remove the tooltip by applying the CSS animation when hovering/removing hover.

Here's an example using JavaScript and CSS:

.tooltip {
  display: none;
  position: absolute;
  padding: 10px;
  color: white;
  border: 1px solid black;
  opacity: 0;
  transition: all 0.2s;
}

.tooltip.show {
  display: block;
  opacity: 1;
}
// Create a tooltip element
const tooltip = document.createElement('span');
tooltip.classList.add('tooltip');

// Add the event listener to the div
const div = document.querySelector('div');
div.addEventListener('mouseover', (e) => {
  // Set the tooltip text
  tooltip.textContent = 'This is my tooltip';

  // Position the tooltip
  tooltip.style.left = e.x + 'px';
  tooltip.style.top = e.y + 'px';

  // Add the tooltip to the body
  document.body.appendChild(tooltip);

  // Add the show class to the tooltip
  tooltip.classList.add('show');
});

div.addEventListener('mouseout', () => {
  // Remove the tooltip from the body
  document.body.removeChild(tooltip);
});

The above is the detailed content of How to Create a Dynamic Tooltip with Fade-in/Fade-out Effects for a Div Element?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn