How can I change CSS with JavaScript for transitions?

Trying:

document.querySelector(".element:hover").style["background"] = "red";

The code didn’t work for me because of the ":hover".
In order to change the background-color of the element when it has hovered, what can I do?

>Solution :

:hover is not something JS can affect. Use CSS instead:

.element:hover {
  background: red;
}

Note that event listeners can also do this, but they would not be as elegant as CSS:

div.addEventListener('mouseover', () => {
  div.classList.add('active');
});

div.addEventListener('mouseout', () => {
  div.classList.remove('active');
});

Try it:

const checkbox = document.querySelector('input');
const div = document.querySelector('div');

div.addEventListener('mouseover', () => {
  if (!checkbox.checked) {
    div.classList.add('active');
  }
});
div.addEventListener('mouseout', () => {
  if (!checkbox.checked) {
    div.classList.remove('active');
  }
});
label:has(:checked) + div:hover,
.active {
  background: red;
}

div {
  margin: 30px 0;
  height: 50px;
  width: 100px;
}
<label>Use CSS: <input type="checkbox" checked></label>

<div>Hover me!</div>

Leave a Reply