Open In App

How to Scroll to Bottom of Div in JavaScript ?

Last Updated : 04 Mar, 2024
Comments
Improve
Suggest changes
1 Like
Like
Report

Scrolling to the bottom of a div is a common task in web development, especially when dealing with chat applications, message boards, or any content where new information is frequently added at the bottom.

There are several approaches to scrolling to the bottom of the div in JavaScript which are as follows:

Using scrollTop Property

The scrollTop property of a div element represents the number of pixels the content of the div is scrolled from its top. By setting this property to the div's scrollHeight, we can scroll to the bottom.

Syntax:

// Get the div element
let divElement = document.getElementById('divId');
// Scroll to the bottom of the div
divElement.scrollTop = divElement.scrollHeight;

Example: To demonstrate the use of the scrollTop Property to scroll to the bottom of the div.

Output:

mainScroll
Scroll to the bottom of the div.

Using scrollIntoView Method

The scrollIntoView method is available on DOM elements. By default, this method scrolls the element into view, but we can specify options to control the scrolling behavior. In our case, we want to scroll to the bottom, so we pass block: 'end'.

Syntax:

let divElement = document.getElementById('divId');
divElement.scrollIntoView({ behavior: 'smooth', block: 'end' });

Example: To demonstrate the use of the scrollIntoView Property to scroll to the bottom of the div.

Output:

mainScroll
Scroll to the Bottom of the div

Next Article

Similar Reads