Flex Flex - 5 months ago 10
Javascript Question

How can I rotate the image in css when it is outside of ul li list

It seems very easy for others but I can't figure it out. I want to rotate the image which is outside of

ul
list when hover on
li > a
. Thank you in advance.

<div class="container">
<ul id="mylist" data-angle="all">
<li class="item"><a href="#home">A</a></li>
<li class="item"><a href="#home">B</a></li>
<li class="item"><a href="#home">C</a></li>
<li class="item"><a href="#home">D</a></li>
<li class="item"><a href="#home">E</a></li>
</ul>
<a href="#link" class="button">
<img src="~/assets/logo/compass.png" />
</a>
</div>

Answer

Here's a JS solution. As mentioned in my comments, since the image is outside of the list, and the anchor elements you're hovering over within that list aren't siblings or parents of the image of course, it's not possible to target the image with pure CSS.

var els = document.getElementsByClassName("item");
for(var i = 0; i < els.length; i++) {
  var btnImg = document.getElementById("rotateImg");
  els[i].addEventListener("mouseover", function() {
    btnImg.className += " rotate";
  }, false);
  els[i].addEventListener("mouseout", function() {
    btnImg.classList.remove("rotate");
  }, false);
}
#rotateImg.rotate {
    -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    transform: rotate(180deg);
}
<div class="container">               
     <ul id="mylist" data-angle="all">
          <li class="item"><a href="#home">A</a></li>
          <li class="item"><a href="#home">B</a></li>
          <li class="item"><a href="#home">C</a></li>
          <li class="item"><a href="#home">D</a></li>
          <li class="item"><a href="#home">E</a></li>
     </ul>
     <a href="#link" class="button">
          <img id="rotateImg" src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRs5uw4irxGko9F06bx4-M7T8eka0R0PK79NAj2rigANKGhQs_BGwAvZg0" />
     </a>
</div>

The above JS loops through each instance of an anchor element within each list item and adds event listeners to each (hover and no hover). If a user hovers over an anchor element, the image which is outside the list rotates 180 degrees. Once the user moves their mouse away from the anchor element, the class is removed.