We can use jQuery to get the top position of an element easily using the offset() method.

$('#div1').offset();

The offset method will return the coordinates of the element relative to the page. We can then get the top coordinate from this method.

$('#div1').offset().top;

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery('#div1').offset().top;

Using jQuery 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:


Get top position
Add margin

In the JavaScript code, when a user clicks a button, we will run a function that we will create.

In the first function, we will get the top position of the element by using the jQuery offset() method to return the coordinates of the element, and then get the top coordinate. We will show this number to the user using the text() method.

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 css method.

Here is the jQuery and JavaScript code:

$('#click-me1').click(function(){
  var topPosition = $('.box').offset().top;
  $('#result').text(topPosition);
});
$('#click-me2').click(function(){
  var marginTop = $('.box').css('margin-top');
  //The number we get will have px at the end. This code removes it
  var topNumber = Number(marginTop.substring(0,marginTop.indexOf('px')));
  $('.box').css('margin-top', ((topNumber + 20) + 'px'));
});

The final code and output for this example is below:

Code Output:

Get top position

Add margin

Full Code:


Get top position
Add margin

Hopefully this article has helped you understand how to use jQuery to get the top position of an element.

Categorized in:

jQuery,

Last Update: February 26, 2024