Search code examples
javascripthtmlcsssvg

Change color of SVG when hover on parent element


I have menu. Each menu item has SVG image and text. SVG is embedded using <object>

<ul id="menu-content" class="menu-content collapse out">
  <li id="calculator">
    <a href="#">
      <tr>
        <td>
          <object type="image/svg+xml" data="assets/calculator.svg">
          </object>
        </td>
        <td class="menu-option">
          <span class="menu-option">
            Pricing & Services
          </span>
        </td>
      </tr>
    </a>
  </li>
  .....
</ul>

When I hover on menu item, background color of this item changes. But I also need to change SVG color. For now I know how to change SVG color when you hover exactly on it. But what to do when I hover on parent element.


Solution

  • So what I did is: 1) Made sure the application is being run on server (I use http server) 2) In index.html I gave id to SVG (id='hat') and parent element (id='m-i-hat'):

    <li id="m-i-hat">
      <a href="#" class="menu-item">
        <object class="menu-icon" id="hat" type="image/svg+xml" data="assets/hat.svg">
        </object>
    

    3) in Index.js :

    $(document).ready(function() {
    var hat = document.getElementById("hat");
    var parent_hat = document.getElementById("m-i-hat")
    
    // It's important to add an load event listener to the object,
    // as it will load the svg doc asynchronously
    hat.addEventListener("load",function(){
      // get the inner DOM of image
      var svgDoc = hat.contentDocument;
      // get the inner element by id (in my svg I have a path i need to change with 
      //id='Hat')
      var area = svgDoc.getElementById("Hat");
      // add behaviour
      parent_hat.addEventListener("mouseover",function(){
       area.style.fill = '#fff'
      });
      parent_hat.addEventListener('mouseout', function(){
       area.style.fill = '#50BC99'
      })
    });