We can use JavaScript to scroll to the bottom of a div by using the scrollTo method along with the offsetTop and offsetHeight properties.

window.scrollTo({ top: (topPositionOfDiv+heightOfDiv), behavior: 'smooth' });

Let’s say I have the following HTML:

Div to scroll to the bottom of.

To scroll to the bottom of the div, we can use the scrollTo() method. Since we need to scroll to the bottom of the div, we need to get the top position of the div, by using the offsetTop property, and the height of the div, using the offsetHeight property.

We then add these numbers together to get the top number for our scrollTop() method.

Here is the JavaScript code:

var topOfDiv = document.getElementById("div1").offsetTop;
var divHeight = document.getElementById("div1").offsetHeight;
window.scrollTo({ top: (topOfDiv+divHeight), behavior: 'smooth' });

Note that we can also do this with jQuery using the animate() and offset() methods.

Using JavaScript to Scroll to Bottom of Div With a Click

Let’s say we have the following HTML code and we want to scroll smoothly to the bottom of the div. We will add some styles to the div to make it a box.


Scroll

We can utilize both an onclick event method along with the Window scrollTo() method to scroll to the bottom of the div.

We will also need to use the offsetTop property to get the top position of the div on the screen. Since we want the bottom position of the div, we also need to use the offsetHeight property to get the height of the div. We add the height to the top position of the div to get the point we need to scroll to.

Below is the JavaScript code which will allow the user to scroll to the bottom of our box div:

function scrollToBottom() {
  var topOfDiv = document.getElementById("box").offsetTop;
  var divHeight = document.getElementById("box").offsetHeight;
  window.scrollTo({ top: (topOfDiv+divHeight), behavior: 'smooth' });
};

The final code and output for this example of how to scroll to the bottom of a div using JavaScript is below.

Code Output:

Scroll

Full Code:


Scroll

Hopefully this article has been useful for you to understand how to use JavaScript to scroll to the bottom of div.

Categorized in:

JavaScript,

Last Update: February 26, 2024