JavaScript Window scrollY property

The JavaScript Window scrollY property is a read-only property that returns the current vertical scroll position of the document. It is commonly used to determine the current scroll position of the document, or to scroll the document to a specific position.

Here are some examples of how the scrollY property can be used in JavaScript code:

  1. To retrieve the current vertical scroll position of the document, you can use the following code:
var y = window.scrollY;

// the value of y will be the current vertical scroll position of the document
  1. To scroll the document to a specific vertical position, you can use the following code:
// calculate the desired scroll position
var x = window.scrollX;
var y = (document.body.scrollHeight - window.innerHeight) / 2;

// scroll the document to the calculated position
window.scrollTo(x, y);
  1. To center the document vertically on the screen, you can use the following code:
// calculate the desired scroll position
var x = window.scrollX;
var y = (document.body.scrollHeight - window.innerHeight) / 2;

// scroll the document to the calculated position
window.scrollTo(x, y);

Overall, the scrollY property provides a convenient way to retrieve and manipulate the vertical scroll position of the document. It can be used for tasks such as centering the document, scrolling it to a specific position, or other operations that require the vertical scroll position of the document.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: