Search code examples
javascriptattributesfill

Why value of my attribute doesn't change?


I've wanted to add something like new tab button but I don't know how to change color of it in JS code. My element:

<svg width="10rem" height="10rem" viewBox="0 0 16 16" class="bi bi-plus- 
    square" fill="gray" xmlns="http://www.w3.org/2000/svg">
                       <path fill-rule="evenodd" d="M14 1H2a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 
     1 0 0 0 1-1V2a1 1 0 0 0-1-1zM2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 
   0- 
    2-2H2z"/>
                       <path fill-rule="evenodd" d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h- 
     3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/>
                   </svg> 

My JS:

    $('svg').on('mouseenter', 'svg', function() {
        this.fill = 'black';
    }).on('mouseleave', 'svg', function() {
        this.fill = 'gray';
    })
    

Solution

  • You need to alter the style of the SVG, not the property itself. Your event listener was also looking for a nested element.

    $('svg').on('mouseenter', function() {
      this.style.fill = 'black';
    }).on('mouseleave', function() {
      this.style.fill = 'gray';
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <svg width="10rem" height="10rem" viewBox="0 0 16 16" class="bi bi-plus- 
        square" fill="gray" xmlns="http://www.w3.org/2000/svg">
      <path fill-rule="evenodd" d="M14 1H2a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 
         1 0 0 0 1-1V2a1 1 0 0 0-1-1zM2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 
       0- 
        2-2H2z"/>
      <path fill-rule="evenodd" d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h- 
         3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/>
    </svg>