@jerad
To create a hover effect in JavaScript, you can use the mouseenter
and mouseleave
events to listen for when the cursor enters or leaves an element. Here's an example of how you can implement a simple hover effect using JavaScript:
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<!DOCTYPE html> <html> <head> <style> .box { width: 200px; height: 200px; background-color: red; transition: background-color 0.3s ease; } .box:hover { background-color: blue; } </style> </head> <body> <div class="box"></div> <script src="script.js"></script> </body> </html> |
JavaScript (script.js
):
1 2 3 4 5 6 7 8 9 |
const box = document.querySelector('.box'); box.addEventListener('mouseenter', () => { box.style.backgroundColor = 'blue'; }); box.addEventListener('mouseleave', () => { box.style.backgroundColor = 'red'; }); |
In this example, the box
element will change the background color to blue when the cursor enters it (mouseenter
event), and revert back to red when the cursor leaves it (mouseleave
event). The transition
property in the CSS ensures a smooth transition between colors.