Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output the Scroll Position on Console [duplicate]

I am trying to output the scroll position, but my solution doesn't seem to work as expected. What am I doing wrong ?

$(document).ready(function() {
    var tempScrollTop = $(window).scrollTop();
    function example() {
        console.log("Scroll from Top: " + tempScrollTop.toString());
    };
});
<body>      
    <p>some text</p>
    <!-- there are many <p> elements -->
    <p>some text</p>        
</body>

Whenever I scroll upwards or downwards the script does't output on the console.

like image 363
rozerro Avatar asked Feb 14 '16 14:02

rozerro


People also ask

How do you get the scroll position?

To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.

How do you get the scroll position of an element in React?

The easiest way to do so - is by checking if the window is defined . Here we check if it runs inside the browser otherwise, just return { x: 0, y: 0 } default values. The next part is straight forward, we check if the user requested the scroll position of the entire page or any specific element inside it.

What is $( window scrollTop ()?

scrollTop property gets or sets the number of pixels that an element's content is scrolled vertically. An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0 .


1 Answers

Firstly you never call the example() function so it will never execute. You need to call the example() function under the scroll event of the element required. Secondly you need to update the value of the tempScrollTop variable inside the function. Try this:

$(window).scroll(example);

function example() {
  var tempScrollTop = $(window).scrollTop();
  console.log("Scroll from Top: " + tempScrollTop.toString());
};
html, body {
  height: 2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
like image 130
Rory McCrossan Avatar answered Sep 18 '22 12:09

Rory McCrossan