Scroll to bottom of div?

javascript

To scroll to the bottom of a div element using JavaScript or jQuery, you can use the scrollTop property of the element or the scrollTop() method of jQuery. Here’s an example:

<!DOCTYPE html>
<html>
<head>
	<title>Example</title>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<style>
		#myDiv {
			height: 100px;
			overflow-y: scroll;
		}
	</style>
</head>
<body>
	<div id="myDiv">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut nisi a nulla venenatis fermentum. In hac habitasse platea dictumst. Fusce molestie, dui vitae euismod pellentesque, ipsum sapien consectetur massa, at imperdiet arcu nunc in neque. Sed ultrices quam vitae justo convallis, id tristique felis gravida. Suspendisse sem ante, porttitor et rhoncus vel, tempor in magna. Aenean dictum bibendum lacinia. Ut ut blandit nulla. Sed at est ut turpis sollicitudin ullamcorper non non ipsum. In hac habitasse platea dictumst. Nam dignissim fermentum purus, id volutpat dolor bibendum nec. Nam porta, mauris quis varius volutpat, diam diam mattis massa, id commodo elit elit id elit.</p>
	</div>
	<button id="scrollBtn">Scroll to Bottom</button>
	<script>
		$(document).ready(function(){
			$("#scrollBtn").on("click", function(){
				$("#myDiv").scrollTop($("#myDiv")[0].scrollHeight);
			});
		});
	</script>
</body>
</html>

In this example, we first create a div element with an id of myDiv and set its height to 100px and overflow-y to scroll, so that it has a vertical scrollbar.

We then create a button with an id of scrollBtn that triggers the scrolling action.

We use the $(“#myDiv”).scrollTop($(“#myDiv”)[0].scrollHeight) statement in the event listener to scroll the #myDiv element to the bottom. The scrollTop() method sets the vertical scrollbar position to the specified value, which in this case is the scrollHeight property of the #myDiv element, representing the total height of the element including its overflow content.

Note that you can customize the element and event listener to suit your specific needs.