Home > Article > Web Front-end > How to Automatically Scroll a DIV to the Bottom When Data is Added?
When displaying data within a limited-height DIV, it's often desirable to have the DIV automatically scroll to the end as new data is added. This enhances the user experience and ensures that the latest information is visible without manual scrolling.
To enable vertical scrolling within the DIV, you need to set its CSS overflow-y property to "visible" and specify a fixed height. For example:
#data { overflow-x: hidden; overflow-y: visible; height: 500px; }
To automatically scroll the DIV to the bottom on data addition, you can use the following JavaScript code:
function scrollToBottom(element) { element.scrollTop = element.scrollHeight; }
This function accepts a DOM element as an argument and sets its scrollTop property equal to its scrollHeight property. This causes the element to scroll all the way to the bottom.
If you don't know precisely when data will be added to the DIV, you can call the scrollToBottom function at regular intervals, for example:
window.setInterval(function() { var elem = document.getElementById('data'); scrollToBottom(elem); }, 5000); // Run every 5 seconds
Alternatively, if you control when data is added, you can simply call the scrollToBottom function after adding new data.
The above is the detailed content of How to Automatically Scroll a DIV to the Bottom When Data is Added?. For more information, please follow other related articles on the PHP Chinese website!