Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Mouseenter and Mouseleave Visual Example</title> <style> #parent { width: 400px; height: 300px; background-color: lightblue; /* Initial background color */ padding: 20px; box-sizing: border-box; position: relative; display: flex; justify-content: space-around; align-items: center; transition: background-color 0.3s ease; } .child { width: 90px; height: 90px; background-color: lightsalmon; display: flex; justify-content: center; align-items: center; transition: background-color 0.3s ease; } #feedback { position: fixed; bottom: 10px; left: 10px; background: white; padding: 10px; border: 1px solid #ccc; font-family: Arial, sans-serif; } </style> </head> <body> <div id="parent"> Parent Element <div class="child">Child 1</div> <div class="child">Child 2</div> <div class="child">Child 3</div> </div> <div id="feedback">Hover over elements to see interactions.</div> <script> const parent = document.getElementById('parent'); const children = document.querySelectorAll('.child'); const feedback = document.getElementById('feedback'); parent.addEventListener('mouseenter', function() { parent.style.backgroundColor = 'cyan'; // Highlight the parent on mouse enter feedback.textContent = 'Mouse entered the parent element'; }); parent.addEventListener('mouseleave', function() { parent.style.backgroundColor = 'lightblue'; // Revert color on mouse leave feedback.textContent = 'Mouse left the parent element'; }); // Update feedback for child interactions children.forEach(child => { child.addEventListener('mouseenter', function() { feedback.textContent = `Mouse entered ${this.textContent}`; this.style.backgroundColor = '#ffcccb'; // Highlight child on mouse enter }); child.addEventListener('mouseleave', function() { feedback.textContent = `Mouse left ${this.textContent}`; this.style.backgroundColor = 'lightsalmon'; // Revert child color on mouse leave }); }); </script> </body> </html>