Search code examples
javascriptrotationhoverinnerhtmlonmouseover

JAVASCRIPT Incrementing innerHTML number onmouseover and back to 0 onmouseout


I can't seem to find a solution anywhere.. Basically I have a meter gauge with a needle which when hovered on, rotates. That I got working fine with CSS, though if anyone can guide me on how to do it in Javascript I appreciate.

Most importantly, I need the number to go up ( like a car gauge ) onmouseover and back down onmouseout using innerHTML. So how do I make use of a range of numbers in Javascript? I need it to go from 0 to 270.

Thanks in advance :)

HTML:

<div id="all">
<svg viewBox="0 0 113 111">
  <style>
    .st3{fill:#17ceff}.st4{fill:none}
  </style>

  <path d="M64.2 56.3c0 4.4-3.6 8-8 8-1.4 0-2.7-.4-3.9-1L31.7 80.6l17.5-20.5c-.6-1.1-1-2.4-1-3.8 0-4.4 3.6-8 8-8s8 3.5 8 8z" fill="#252626" stroke="#fff" stroke-width=".47" stroke-miterlimit="10" id="needle"/>

  <div class="result" id="result">0</div>
</svg>
</div>

CSS:

 #needle {
      transform-origin: inherit;
     transition: 0.70s;
 }

#needle:hover {
    transition: 0.70s;
    transform: rotate(270deg);
}

Solution

  • <div class="whole-container">
            <div class="meter">0</div>
            <div class="needle"></div>
        </div>
    

    Jquery

        var inte;
        $('.whole-container').on('mouseover', function () {
            clearInterval(inte);
            var i = parseInt($('.meter').text());
            inte = setInterval(() => {
                $('.meter').text(i);
                $('.needle').css('transform', 'rotate(' + i + 'deg)');
                if (i == 270) clearInterval(inte);
                i++;
            }, 100);
        });
        $('.whole-container').on('mouseout', function () {
            clearInterval(inte);
            var i = parseInt($('.meter').text());
            inte = setInterval(() => {
                $('.meter').text(i);
                $('.needle').css('transform', 'rotate(' + i + 'deg)');
                if (i == 0) clearInterval(inte);
                i--;
            }, 100);
        });
    

    Please make changes to html and script classes/id as needed