Javascript DOM HTML Element offsetTop Property

Introduction

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

Get the offsetTop position of a <div> element:

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#test {//from  w  w w .  j a va2 s.c  o  m
  top: 100px;
  margin: 10px;
  padding: 10px;
  width: 300px;
  position: relative;
  border: 5px solid black
}
</style>
</head>
<body>

<div id="test">
  P:Click the button to get offsetTop for the test div.</p>
  <p><button onclick="myFunction()">Test</button></p>
  <p>offsetTop is: <span id="demo"></span></p>
</div>

<script>
function myFunction() {
  var testDiv = document.getElementById("test");
  document.getElementById("demo").innerHTML = testDiv.offsetTop;
}
</script>

</body>
</html>

The offsetParent element is the nearest ancestor with non-static position.

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

The offsetTop property returns a Number representing the top position of the element in pixels.




PreviousNext

Related