Hover Magic: Change The Background Color with JavaScript When Hovering Over Another Element!

Опубликовано: 31 Октябрь 2024
на канале: CSS Hero
1,179
17

Discover how to add a touch of interactivity to your website by changing the background of a div when hovering over another element using JavaScript! In this tutorial, we'll guide you step-by-step through the process, so you can easily implement this awesome feature. Thanks for watching, and if you found this helpful, don't forget to like, comment, and subscribe for more amazing tutorials! Happy coding! 😊
#webdesign #javascript #tutorial #interactivity #hovermagic #coding #webdevelopment #csshero
Tools:
https://www.csshero.org


CSS code:
To give the transition a silky-smooth feel, just pop this line of code into the body element:

body {
transition: background-color 0.5s ease-in-out;
}

JS Code:

// Get a reference to the body element
var body = document.body;

// Get a reference to the #hero_hover_animation element
var hover_element = document.getElementById("hero_hover_animation");

// Add event listener for mouseover event on the hero_hover_animation element
hover_element.addEventListener("mouseover", function() {
// Change the background color of the body element to yellow
body.style.backgroundColor = "#ffd66b";
});

// Add event listener for mouseout event on the hero_hover_animation element
hover_element.addEventListener("mouseout", function() {
// Reset the background color of the body element to white
body.style.backgroundColor = "#fff";
});