Javascript DOM HTML Element offsetLeft Property

Introduction

The offsetLeft property returns the left position in pixels relative to the left side the offsetParent element.

Get the offsetLeft position of a <div> element:

Click the button to get offsetLeft for the test div.

View in separate window

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

<div id="test">
  
  <p><button onclick="myFunction()">Test</button></p>
  <p>offsetLeft is: <span id="demo"></span></p>
</div>

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

</body>
</html>

The offsetParent element is the nearest non-static ancestor.

To return the top position of an element, use the offsetTop property.

The offsetLeft property returns a Number representing the left position of the element in pixels.




PreviousNext

Related