0

i've got some code from codepen where a progress bar fills up depending on a given number out of 100. i want it to activate when it is scrolled to, instead of on reload, which it currently is set to. I cant find anything on here already. Javascript is new to me, so trying to get the hang of it, thanks

$('.progress-wrap').each(function(){
    percent = $(this);
    bar = $(this).children('.progress-bar');
    moveProgressBar(percent, bar);
});

  // on browser resize...
  $(window).resize(function() {
    $('.progress-wrap').each(function(){
        percent = $(this);
        bar = $(this).children('.progress-bar');
        moveProgressBar(percent, bar);
    });
  });

  // SIGNATURE PROGRESS
  function moveProgressBar(percent, bar) {
      var getPercent = (percent.data('progress-percent') / 100);
      var getProgressWrapWidth = percent.width();
      var progressTotal = getPercent * getProgressWrapWidth;
      var animationLength = 1000;

      // on page load, animate percentage bar to data percentage length
      // .stop() used to prevent animation queueing
      bar.stop().animate({
          left: progressTotal
      }, animationLength);
  }
<div class="progress-wrap progress star" data-progress-percent="70">
   <div class="progress-bar progress"></div>
   </div>
b.herring
  • 563
  • 2
  • 18
  • Similar to how you do `$(window).resize(function() { ... }`, you can wrap whatever you want to happen on scroll with `$(window).scroll(function() { ... }` – Tyler Roper Sep 26 '18 at 21:02
  • thanks that works. but i may have phrased my question wrong, i want the javascript to be activated when it is scrolled to, not just when i scroll, as the feature is far down the page, so if im at the top, by the time ive scrolled to the feature, it has already activated. @tylerRoper – b.herring Sep 26 '18 at 21:41

2 Answers2

0

Looks like you are using jquery - it would be easier to do this in vanilla javascript like so:

window.onscroll = function (e) {  
// called when the window is scrolled.  
} 

You may want to have a look at: Detect if user is scrolling for jquery options.

alpharomeo
  • 418
  • 5
  • 13
  • Personally I don't see this as any "easier", not to mention it's a pretty bad code smell when you start mixing jQuery and vanilla JS for things like event handling. – Tyler Roper Sep 26 '18 at 21:03
  • Hence the reason why I pointed the user towards the jQuery option from another SO question. It is easier in my opinion - thought including the link might put the user on a learning journey. Agree - not a good idea to mix vanilla and jQuery. – alpharomeo Sep 26 '18 at 21:11
0

This should work:

Replace #someElement with the Id of the element that when in view fires the function you want.

someFunction() is the function that you want to run when the element is in view

$(document).on('scroll', function() {
    if( $(this).scrollTop() >= $('#someElement').position().top ) {
        someFunction();
    }
});
johnchar
  • 547
  • 10
  • 22