0

I am trying to change the background-color of an element when a user hovers over a list item.

The element I am trying to change is not a parent or sibling of the hovered element:

<div>
  <div class="absolute rounded-full w-20 h-20 ball"></div> // Element I am trying to change
     <ul class="flex-row w-full navUl">
          <li class="inline-block mr-10">
            <a href="#" class="py-12 no-underline">
              Menu Item
            </a>
            <ul class="p-4">
              <li class="px-6 py-2"><a href="#">Sub Link</a></li> // Element triggering change
              <li class="px-6 py-2"><a href="#">Sub Link</a></li>
              <li class="px-6 py-2"><a href="#">Sub Link</a></li>
              <li class="px-6 py-2"><a href="#">Sub Link</a></li>
            </ul>
            ...
</div>

I was able to do this with the list item's custom bullet by doing the following:

.navUl li ul li:hover {
      color: red;
      &:before{
           background-color: red;
      }
  }

So I thought doing this would work but it doesn't:

.navUl li ul li:hover {
    & .ball {
      background-color: red;
    }
  }

Project for reference

Eric Nguyen
  • 612
  • 1
  • 7
  • 20

1 Answers1

0

What you are trying to achieve here can only be done using javascript as far as I know by adding a mouseover and mouseout listener to your list items.

let listItems = document.getElementsByClassName(".list-item")
let balls = document.getElementsByClassName(".ball")

listItems.forEach(listItem => {
  listItem.addEventListener("onmouseover", () => {
    balls.forEach(ball => {
      ball.style.backgroundColor = "red"
    })
  })

   listItem.addEventListener("onmouseout", () => {
    balls.forEach(ball => {
      ball.style.backgroundColor = "white"
    })
  })
})

Let me know if you face any issues with this code.

DpK
  • 100
  • 4