We can use JavaScript and the offsetTop property of an element to get the top position of that element.
document.getElementById("div1").offsetTop;
The offsetTop property will return the top position of the element relative to the page.
Note that we can also get the top position of an element using jQuery using the offset() method.
Using JavaScript and the offsetTop property to Get the Top Position of Element With a Click
In this example, we will have a div that will be a box. We will let the user check the top position of the div and also let the user add margin to the top of the div to change its top position.
Here is the simple HTML set up:
In the JavaScript code, when a user clicks a button, we will run a function that we will create. We do this with the help of two onclick events that are attached to each button.
In the first function, we will get the top position of the element by using the offsetTop property to return the top position of the element. We will show this number to the user using the textContent property.
In the second function, we will simply get the top margin of the div, and add 20px to it. We will do this using the marginTop property.
Here is the JavaScript code:
function getTopPosition(){
var topPosition = document.getElementById('box').offsetTop;
document.getElementById('result').textContent = topPosition;
};
function addMargin(){
var marginTop = document.getElementById('box').style.marginTop;
//The number we get will have px at the end. This code removes it
var topNumber = Number(marginTop.substring(0,marginTop.indexOf('px')));
document.getElementById('box').style.marginTop = ((topNumber + 20) + 'px');
};
The final code and output for this example is below:
Code Output:
Full Code:
Hopefully this article has helped you understand more about JavaScript offsetTop.