We can use jQuery to get the bottom 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. To get the bottom position of the element, we will have to add the height of the element to this number, using the height() method.
var bottom = $('#div1').offset().top + $('#div1').height();
If you are using WordPress, don’t forget to change the $ to jQuery as below:
var bottom = jQuery('#div1').offset().top + jQuery('#div1').height();
Using jQuery to Get the Bottom 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 bottom position of the div and also let the user add margin to the top of the div to change its bottom position.
Here is the simple HTML set up:
Get bottom 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 then get the height of the div, and add this number to our top coordinate, to get the bottom value of the div.
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 bottomPosition = $('.box').offset().top + $('.box').height();
$('#result').text(bottomPosition);
});
$('#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:
Full Code:
Get bottom position
Add margin
Hopefully this article has helped you understand how to use jQuery to get the bottom position of an element.