We can use jQuery to get the 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 and left coordinates from this method.
$('#div1').offset().top;
$('#div1').offset().left;
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery('#div1').offset().left;
Using jQuery to Get the Position of an Element With a Click
In this example, we will have a div that will be a box. We will let the user check the position of the div and also let the user add margin to the top and left of the div to change its position.
Here is the simple HTML set up:
Get 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 position of the element by using the jQuery offset() method to return the coordinates of the element, and then get the top and left coordinates. We will show these numbers to the user using the text() method.
In the second function, we will simply get the top and left margins of the div, and add 20px to each. We will do this using the css method.
Here is the jQuery code:
$('#click-me1').click(function(){
var topPosition = $('.box').offset().top;
var leftPosition = $('.box').offset().left;
var textToUser = "Top: " + topPosition + ", Left: " + leftPosition;
$('#result').text(textToUser);
});
$('#click-me2').click(function(){
var marginTop = $('.box').css('margin-top');
var marginLeft = $('.box').css('margin-left');
//The numbers we get will have px at the end. This code removes it
var topNumber = Number(marginTop.substring(0,marginTop.indexOf('px')));
var leftNumber = Number(marginLeft.substring(0,marginLeft.indexOf('px')));
$('.box').css('margin-top', ((topNumber + 20) + 'px'));
$('.box').css('margin-left', ((leftNumber + 20) + 'px'));
});
The final code and output for this example of how to use jQuery to get the position of an element is below:
Code Output:
Full Code:
Get position
Add margin
Hopefully this article has helped you understand how to use jQuery to get the position of an element.