skip to Main Content

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?

3

Answers


  1. :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>
    Login or Signup to reply.
  2. You can use a CSS variable to control the background on hover, which can also be set in JavaScript.

    document.querySelector('button').addEventListener('click', e => {
      document.querySelector('.element').style.setProperty('--background', 'red');
    });
    .element:hover {
      --background: dodgerblue;
      background: var(--background);
    }
    <div class="element">
    Hover over here
    </div>
    <button>Change hover color</button>
    Login or Signup to reply.
  3. An alternative to @inSync ‘s approach.
    In case , you need a pure JS solution , you could use the mouseover event as below :

    const myDiv = document.querySelector(".mydiv");
    
    myDiv.addEventListener("mouseover", (event) => {
      event.target.style.background = "Red";
    });
    <div class="mydiv">
      Hover over me !
    </div>

    Mouseover event : https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseover_event

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search