How to change css of a div with a certain id when hovering over a certain element anywhere in the whole webpage?

Let’s suppose that this is your <div> element:

<div id="myDiv" style="width:100px; height:100px; background:#AAAAAA">
  <!-- Your div content here -->
</div>

Now you have to add this javascript:

// Change color of div on hover
function hover() {
  document.getElementById('myDiv').style.background = "#FFAAAA";
}

// Return the color back to original when the mouse leaves the li
function retorg() {
  document.getElementById('myDiv').style.background = "#AAAAAA";
}

var lists = document.getElementsByTagName('li');
// Add event handlers to the li elements
for (var i = 0; i < lists.length; i++) {
  lists[i].addEventListener("mouseover", hover);
  lists[i].addEventListener("mouseout", retorg);
}

Leave a Comment