Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Increment A Number By 1 On Window Scroll

I have a type of progress tracker sitting fixed on the side of my page and as you scroll, I want the line to gain height (in percentages) as the user scrolls down the page. I am having trouble getting the height to increase by just one as the user scrolls. Here is my current code.

JS

$(window).scroll(function(){
 var number = 0; /* I'd like to increment this by one on scroll */
 // Only start the process when the first section comes into view
 if($("#progress-tracker-nav li").hasClass('active-section')) {
  number++; /* I'd like to increment this by one on scroll */
  $(".progress-line").css('height', number + '%');
 }
})
like image 859
Taylor Foster Avatar asked Dec 23 '22 20:12

Taylor Foster


1 Answers

You have to declare number variable outside of the scroll event handler, because every time when scroll event is fired, the variable value is refreshed.

In your current code, you assign every time 0 value for number variable.

var number = 0;
$(window).scroll(function(){ 
  number++;
  $("#number").text(number + '%');
})
body{
  height:1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="number"></div>
like image 59
Mihai Alexandru-Ionut Avatar answered Dec 28 '22 07:12

Mihai Alexandru-Ionut