Search code examples
javascriptjquerycsssvgsvg-animate

Smooth animate for svg fill


I have an SVG thermometer and I'm trying to animate filling it smoothly for each class.

I did thermometer with toggle classes. I'm trying to animate smoothly up-down, and down-up animation for each class I have.

https://lore1ei.github.io/ -thermometer.

var firstStop = document.getElementById('F1gst1');
percentage = '0%';
firstStop.setAttribute('offset', percentage);
var CountAllCheckboxes = $('.analysis-li').length;
var CountChecked = 0;

$(".analysis-li").click(function() {
  $(this).toggleClass("check");

  CountChecked = $('.analysis-li.check').length;
  percentage = ((CountChecked / CountAllCheckboxes) * 100) + '%';
  firstStop.setAttribute('offset', percentage);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

<svg class="thermometr" id="Layer_1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 44.3 333.8">
  <linearGradient y2="0%" x2="0%" y1="100%" x1="0%" id="F1g">
    <stop stop-color="#00FF00" offset="0%" id="F1gst1"/>
    <stop stop-color="#FFFFFF" offset="0%" id="F1gst2"/> 
  </linearGradient>
  <path fill="url(#F1g)" class="st0" d="M30.5 297.5V4.6c0-2.5-2.1-4.6-4.6-4.6-2.5 0-4.6 2.1-4.6 4.6v292.9c-7.9 2-13.8 9.2-13.8 17.8 0 10.2 8.2 18.4 18.4 18.4s18.4-8.2 18.4-18.4c0-8.5-5.9-15.7-13.8-17.8"/>
  <path fill="url(#F1g)" class="st0"  d="M9 290.2h7.5v.5H9zM9 284.3h7.5v.6H9zM9 278.4h7.5v.5H9zM9 272.5h7.5v.6H9zM0 266.6h16.5v.6H0zM9 260.7h7.5v.5H9zM9 254.8h7.5v.6H9zM9 248.9h7.5v.5H9zM9 243h7.5v.6H9zM0 237.1h16.5v.6H0zM9 231.3h7.5v.5H9zM9 225.4h7.5v.6H9zM9 219.5h7.5v.6H9zM9 213.6h7.5v.6H9zM0 207.7h16.5v.6H0zM9 201.8h7.5v.6H9zM9 195.9h7.5v.6H9zM9 190h7.5v.6H9zM9 184.1h7.5v.5H9zM0 178.2h16.5v.6H0zM9 172.3h7.5v.6H9zM9 166.4h7.5v.5H9zM9 160.5h7.5v.6H9zM9 154.7h7.5v.6H9zM0 148.8h16.5v.6H0zM9 142.9h7.5v.6H9zM9 137h7.5v.5H9zM9 131.1h7.5v.5H9zM9 125.2h7.5v.6H9zM0 119.3h16.5v.5H0zM9 113.4h7.5v.6H9zM9 107.5h7.5v.6H9zM9 101.6h7.5v.5H9zM9 95.7h7.5v.6H9zM0 89.8h16.5v.6H0zM9 83.9h7.5v.6H9zM9 78.1h7.5v.6H9zM9 72.2h7.5v.6H9zM9 66.3h7.5v.6H9zM0 60.4h16.5v.6H0zM9 54.8h7.5v.6H9zM9 48.9h7.5v.6H9zM9 43h7.5v.5H9zM9 37.1h7.5v.6H9zM0 31.2h16.5v.5H0zM9 26h7.5v.6H9zM9 20.1h7.5v.5H9zM9 14.2h7.5v.6H9zM9 8.3h7.5v.6H9zM0  2.4h16.5V3H0z"/>
</svg>


Solution

  • One solution is to animate it using javascript only instead of using css and/or svg-props. For example:

    function anim(fromPercentage) {
       var topLimit = 25;  
       fromPercentage += 1;
       if(fromPercentage < topLimit) {
          $('#F1gst1').attr('offset', fromPercentage + '%');
          setTimeout( function() {
             anim(fromPercentage);
          }, 35);
       }
    };
    
    /*
    * Animates the bar from 10 to 25 percentage.
    * Change the topLimit inside the anim-function to the current desired top level.
    * Also tweek the timeout to get smoother transition.
    */
    anim(10);