How to change the background color of an element, on mousehover event, with vanilla JavaScript?

Here on the forum webpage of SitePoint I try to change the background color of each child element of the top sticky menu, on mousehover event, but I fail to do so with the following code.

document.querySelector('.contents').querySelectorAll('*').forEach( (element)=>{
    element.addEventListener('mousehover', ()=>{
        element.style.background = "red";
    });
});

How to change the background color of an element, on mousehover event, with vanilla JavaScript?

1 Like

There is no mousehover event.

Available mouse events are (not counting click, double click and context menu):

  • onmousedown: A mouse button is pressed over an element
  • onmouseenter: The pointer is moved onto an element
  • onmouseleave: The pointer is moved out of an element
  • onmousemove: The pointer is moving over an element
  • onmouseout: The mouse pointer moves out of an element
  • onmouseover: The mouse pointer is moved over an element
  • onmouseup: The mouse button is released over an element

To make your code work here on SitePoint:

document.querySelectorAll('header a, header li').forEach(element => {
  element.addEventListener('mouseover', () => {
    element.style.background = 'red';
  });
}); 

See also:

3 Likes