Home > Software design >  I want to start JS function when I scroll
I want to start JS function when I scroll

Time:04-17

I have a one-page website with a section for a progress bar. I have a function for animation and all that, and I know how to start it when the page loads. But I don't know how to start it when I scroll to that section.

JS code :

window.onload = function() {
    move();
};

var i = 0;
function move() {
    if (i == 0) {
        i = 1;
        var elem = document.getElementById("myBar");
        var width = 1;
        var id = setInterval(frame, 10);
        function frame() {
            if (width >= 95) {
                clearInterval(id);
                i = 0;
            } else {
                width  ;
                elem.style.width = width   "%";
            }
        }
    }
}

CodePudding user response:

If you want to trigger on scroll, you could do that through jquery.

$(element).scroll(() ={
    function ()
}

But if you want to animate on scroll, I'd advise you to use a library called Gsap. Look in the scrollTrogger document.

CodePudding user response:

Simply use the scroll event on the whole document:

document.addEventListener('scroll', function(e) {
  move();
});

var i = 0;

function move() {
  if (i == 0) {
    i = 1;
    var elem = document.getElementById("myBar");
    var width = 1;
    var id = setInterval(frame, 10);

    function frame() {
      if (width >= 95) {
        clearInterval(id);
        i = 0;
      } else {
        width  ;
        elem.style.width = width   "%";
      }
    }
  }
}
<div style="height:1000px;width:100%;">

<div style="height:200px">padding</div>
  <div id="myBar" style="background:green;">my bar</div>

</div>

  • Related