Javascript DOM HTML Element offsetLeft Property for div element

Introduction

Get the position of a a <div> element:

Click the button to get the left and top offsets for the test div.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#test {//from w w w .j ava  2  s.  c  om
  left: 100px;
  top: 50px;
  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 id="demo">offsetLeft: <br>offsetTop: </p>
</div>

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

</body>
</html>



PreviousNext

Related