In this tutorial we will see how to Get Scroll Position From Top with JavaScript. Window scrollY property can be used to calculate the pixels the page has scrolled from the top of the browser.
Table of Contents
Window scrollY Property
The Window scrollY Property is read only property which returns the exact distance in pixels the web page has scrolled from the top.
In this example we have also used innerHeight property to measure the size of browser window while scrollY property will get us the position scrolled from top.
Both values are in pixels and their sum is equal to the total size of document or web page.
We have set the size of body of our page using CSS.
HTML Code
HTML Code is given below, in this code we have a main div with two paragraph tags inside. First paragraph tag will display the size of browser window while the second paragraph will display the scrolled distance from top in pixels.
Note that body is given height using CSS and the onscroll event is used inside body tag which will trigger a JavaScript function on scroll event.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Get Scroll Position From Top</title>
<style>
*
{
margin: 0;
padding: 0;
}
body
{
height: 2000px;
}
.output
{
position: fixed;
}
</style>
</head>
<body onscroll="getScrollPos()">
<div class="output">
<p id="height"></p>
<p id="position"></p>
</div>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
JavaScript Code is given below, in this code window.innerHeight will return the height of browser screen and window.scrollY will return the scrolled position from top in pixels.
getElementById() method is used to select the paragraph tags while innerHTML is used to display the values inside them.
<script>
const browserHeight = window.innerHeight;
var output = document.getElementById('height');
output.innerHTML = "Browser Height: " + browserHeight + "px";
function getScrollPos()
{
const scroll = window.scrollY;
var output = document.getElementById('position');
output.innerHTML = "Scrolled: " + scroll + "px";
}
</script>
Demo
Video Tutorial
Watch video tutorial on how to Get Scroll Position From Top using JavaScript.