JavaScript Answers

How to change :hover CSS properties with JavaScript?

Spread the love

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:

  1. Define the CSS rules for the hover state in a separate class.
  2. Use JavaScript to add or remove this class to the element based on certain events, such as mouseenter and mouseleave.

Here’s an example:


<!DOCTYPE html>
<html lang="en">
  <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">
  <div id="myElement">Hover over me</div>

  <script src="script.js"></script>

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.addEventListener('mouseleave', function() {
  // Remove the 'hover' class when mouse leaves the element

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *