What is offsetTop in JavaScript

Properties offsetTop and offsetLeft of window

We were able to determine the position of an element on a website using and. The position is always determined depending on the associated parent element. If we use the query directly within the body, we determine the distance from the top right corner. The output value corresponds to pixels.

Both properties are made available by our browser object "document" and can only be read.

Even if the browser window is scrolled, these values ​​do not change.

Method:

  1. Select an element on the website (this is often useful).
  2. The pixel distance to the parent element can now be determined from this element via or.

In the following example we get the distance up for our control area.

If we now want to have the number of pixels output, we have to apply an "addEventListener" to the load function. We can output the current number in the ID area “ylage”.

What can we do with this information for the design of our website?

Fix the menu line at the top after scrolling

We want our menu bar (control element) at the top not to disappear from the visible area but to “stick”.

The finished example is available for testing at:
https://www.javascript-kurs.de/beispielcode/beispiel-offsetTop.htm

The position of an element becomes interesting when the window has been scrolled and the element has moved accordingly. These current X and Y values ​​of an element after scrolling on a website are easy to determine. For this, the property can be read out via JavaScript via and, which we need for our practical example below.

If we want to display the current number of pixels, we have to put an "addEventListener" on the scroll function. We can output the current number in the ID area “ylage”.

So here we need our offsetTop value as well as the value of pageYOffset:

  • Distance from above via offsetTop
  • current distance by scrolling over pageYOffset

We combine both values ​​in our previous JavaScript program:

If we now scroll up and down on our HTML page, we see how the second value changes. If the second value becomes larger than the first value, our control element disappears from the visible area.

Now we can easily compare both values ​​and, if necessary, add a CSS class to our control element to fix the bar or remove the class again.

As soon as the value of pageYOffset is equal to or greater than offsetTop, we stick our nav element using CSS:

For this we create the class

We make the area semi-transparent so that we can also see how the content is scrolled up behind it.

And here is the complete code:

pageXOffset & pageYOffset and old browsers or the good old IE before version 9

Of course, the old Microsoft browser versions spit in the soup. Before version 9, these have different commands for reading out the positions. We can deal with this problem:

And if it is for the X direction, then there is "document.documentElement.scrollLeft" for the old IE versions