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.
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.
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.
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 .
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With