muhaymin khan
muhaymin khan

Reputation: 101

jQuery increase and decrease value based on 0.05 on scrolling with jquery

i am trying to make 1 counter with the value 0.05 when page scroll it should increase like this 0.10, 0.15, 0.20** and so on and when i scroll top again it should be decrease in same way like this 0.15, 0.10, 0.05** and when the screen touch top it should be 0 how to achieve this with jquery

var counter = 0
$(window).scroll(function(){
    var a = $(this).scrollTop();
    var counterIncrement = counter += 0.05;
    $("h1").text(counterIncrement.toFixed(2));
})
 h1{
    position: fixed;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
}
div{
    height: 1500px;
}
<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>

    </head>
    <body>
        <h1>0</h1>
        <div></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </body>
    </html>

Upvotes: 0

Views: 975

Answers (1)

persian-theme
persian-theme

Reputation: 6638

You need to decrease the value when the scroll is up and increase the value when the scroll is down.

To identify a variable that holds the value of the last scroll point, you must use the scroll down if the new value is larger and the scroll up if the new value is smaller.

var counter = 0;
var lastPointScroll = 0;
$(window).scroll(function(){
    var a = $(this).scrollTop();
    
    if(a == 0)
      var counterIncrement = counter = 0;
    else if(a > lastPointScroll)
      var counterIncrement = counter += 0.05;
    else
      var counterIncrement = counter -= 0.05;
   
      
    lastPointScroll = a;
    $("h1").text(counterIncrement.toFixed(2));
})
h1{
    position: fixed;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
}
div{
    height: 1500px;
}
<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>

    </head>
    <body>
        <h1>0</h1>
        <div></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </body>
    </html>

Upvotes: 2

Related Questions