Home >Web Front-end >CSS Tutorial >How to Create a Dynamic Tooltip with Fade-in/Fade-out Effects for a Div Element?
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?
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:
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!