To change the :hover
CSS properties with JavaScript, you can add or remove classes to the elements you want to modify. Here’s how you can achieve it:
- Define the CSS rules for the hover state in a separate class.
- Use JavaScript to add or remove this class to the element based on certain events, such as
mouseenter
andmouseleave
.
Here’s an example:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Hover CSS with JavaScript</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div id="myElement">Hover over me</div>
<script src="script.js"></script>
</body>
</html>
CSS (styles.css):
/* Define the default styles */
#myElement {
width: 200px;
height: 100px;
background-color: blue;
color: white;
text-align: center;
line-height: 100px;
}
/* Define the styles for the hover state */
#myElement.hover {
background-color: red;
}
JavaScript (script.js):
// Get a reference to the element
var element = document.getElementById('myElement');
// Add event listeners for mouseenter and mouseleave events
element.addEventListener('mouseenter', function() {
// Add the 'hover' class when mouse enters the element
element.classList.add('hover');
});
element.addEventListener('mouseleave', function() {
// Remove the 'hover' class when mouse leaves the element
element.classList.remove('hover');
});
In this example, when the mouse enters the element (mouseenter
event), the hover
class is added to the element, changing its background color to red.
When the mouse leaves the element (mouseleave
event), the hover
class is removed, reverting the background color to blue.
Adjust the CSS properties and JavaScript code to suit your specific requirements.