Home >Web Front-end >JS Tutorial >How to Get the Scrollbar Position in JavaScript?

How to Get the Scrollbar Position in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-14 16:30:02219browse

How to Get the Scrollbar Position in JavaScript?

Getting Scrollbar Position with JavaScript

To determine the current view position on a webpage, you can ascertain the scrollbar position using JavaScript. This guide will demonstrate how to achieve this.

To obtain the scrollbar position, you can utilize the element.scrollTop and element.scrollLeft properties. These properties return the vertical and horizontal offset of the element element that has been scrolled, respectively. If you're interested in the full page, element can be set to document.body.

To determine percentages, you can compare the offset values to element.offsetHeight and element.offsetWidth. Once again, element can be the document body.

Here's an example code snippet that demonstrates the usage of these properties:

// Get the vertical scroll position of the document
const verticalScrollPos = document.body.scrollTop;

// Get the horizontal scroll position of the document
const horizontalScrollPos = document.body.scrollLeft;

// Get the height and width of the document
const documentHeight = document.body.offsetHeight;
const documentWidth = document.body.offsetWidth;

// Calculate the percentage of the vertical scroll position
const verticalScrollPercentage = (verticalScrollPos / documentHeight) * 100;

// Calculate the percentage of the horizontal scroll position
const horizontalScrollPercentage = (horizontalScrollPos / documentWidth) * 100;

The above is the detailed content of How to Get the Scrollbar Position in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn