THE WORLD'S LARGEST WEB DEVELOPER SITE

Element offsetTop Property

❮ Element Object

Example

Get the offsetTop position of a <div> element:

var testDiv = document.getElementById("test");
document.getElementById("demo").innerHTML = testDiv.offsetTop;
Try it Yourself »

Definition and Usage

The offsetTop property returns the top position (in pixels) relative to the top of the offsetParent element.

The returned value includes:

  • the top position, and margin of the element
  • the top padding, scrollbar and border of the offsetParent element

Note: The offsetParent element is the nearest ancestor that has a position other than static.

Tip: To return the left position of an element, use the offsetLeft property.


Browser Support

Property
offsetTop Yes 8.0 Yes Yes Yes

Syntax

Return the top offset position:

object.offsetTop


Technical Details

Default Value: no default value
Return Value: A Number, representing the top position of the element, in pixels
DOM Version: CSSOM

More Examples

Example

Get the position of a a <div> element:

var testDiv = document.getElementById("test");
var demoDiv = document.getElementById("demo");
demoDiv.innerHTML = "offsetLeft: " + testDiv.offsetLeft + "<br>offsetTop: " + testDiv.offsetTop;
Try it Yourself »

Example

Create a sticky navigation bar:

// Get the navbar
var navbar = document.getElementById("navbar");

// Get the offset position of the navbar
var sticky = navbar.offsetTop;

// Add the sticky class to the navbar when you reach its scroll position. Remove the sticky class when you leave the scroll position.
function myFunction() {
  if (window.pageYOffset  >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}
Try it Yourself »

❮ Element Object