-1

I'm making a system where a user scrolling and their score increases. There is a counter which I would like to increase the value of using jQuery (so that the page does not need to refresh) when the scrolling.

How would I go about this?

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
jQuery(function() {
    jQuery(window).scroll(function(){
        if(jQuery(this).scrollTop() > 2000) {
            // ......
        }
    }); 
}); 
</script>

It should increase by every 2000px.

eisbehr
  • 12,243
  • 7
  • 38
  • 63
abukotsh
  • 45
  • 7
  • `var counter = 0; ` outside the scroll event and then `counter++;` inside your `if` ?? – N. Ivanov Mar 27 '18 at 14:33
  • Are you sure this is what you want? What if the user presses spacebar to go down a page, or end key to go to the bottom? Also scroll events are **not** guaranteed to be raised for every pixel. You might be better binding to `mousewheel` ? https://stackoverflow.com/a/15629039/2181514 – freedomn-m Mar 27 '18 at 14:42
  • 1
    As she uses `scrollTop` it's not actually needed that `scroll` is triggered on every pixel. But beside this, you're correct. @freedomn-m – eisbehr Mar 27 '18 at 14:46

2 Answers2

1

It's not a real counter, you just need to divide scrollTop by 2000 to get a value.

jQuery(function($) {
    $(window).on('scroll', function() {
        var count = Math.floor($(this).scrollTop() / 2000);
        $('#counter').text(count);
    });
});
#counter {
  position: fixed;
}

#content {
  width: 10px;
  height: 20000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter">0</div>
<div id="content"></div>

If you want too keep the highest amount, just increase, but don't decrease. You could simply use a helper variable for this, called highscore in my example:

jQuery(function($) {
    var highscore = 0;

    $(window).on('scroll', function() {
        var count = Math.floor($(this).scrollTop() / 2000);

        if(count > highscore) {
            $('#counter').text(highscore = count);
        }
    });
});
#counter {
  position: fixed;
}

#content {
  width: 10px;
  height: 20000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter">0</div>
<div id="content"></div>
eisbehr
  • 12,243
  • 7
  • 38
  • 63
0
var counter = 0;
jQuery(function() {
    var nextIncrmenet = 2000;
    jQuery(window).scroll(function(){
        if(jQuery(this).scrollTop() > nextIncrmenet) {
            counter = counter + 1;
            nextIncrmenet = nextIncrmenet + 2000;
        }
    }); 
});
Ankush G
  • 989
  • 9
  • 14