Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading