I have a container and I have a function using scrollTop
that will scroll to the bottom of the container when it is called.
function updateScroll(){
var objDiv = document.getElementById("con-result");
objDiv.scrollTop = objDiv.scrollHeight;
};
How do I add smooth scrolling functionality to this? I know that there is behavior: smooth
available but I don’t know how to add this to what i’m trying to do as it is available using window.scrollTo().
Any help would be great!
4
Answers
Can you try this
Set the scroll behavior before calling updateScroll
Call this function whenever you want to scroll
To scroll to the bottom of the element you can use
scrollTo()
along with thebehaviour: smooth
property:To add smooth scrolling functionality to the scrollTop assignment in JavaScript, you can’t directly use the behavior: smooth option since that’s part of the scrollTo options object available in the newer Scroll API, which doesn’t apply to the scrollTop property.
However, you can achieve a smooth scrolling effect by using
Element.scrollIntoView()
with behavior: ‘smooth’, or by using the newer scrollTo with the appropriate options if you’re targeting modern browsers.Here’s how you could do it using
scrollIntoView():
And here is how you could do it using the scrollTo with the top property set to scrollHeight:
Both of these methods will add a smooth scrolling animation to your container. Keep in mind that scrollIntoView and the options object for scrollTo may not be supported in all browsers, especially older ones. Always check for compatibility if you expect your website to be used on older browsers or consider polyfills for broader support.
Also, if you’re dynamically adding content to the container and want to scroll to the bottom as new content is added, make sure to call updateScroll after the new content has been appended to ensure accurate scrolling.
Without using directly CSS you can use
element.scroll()
by setting its top property toelement.scrollHeight
. like this:Or you can also use
element.scrollIntoView()
, and setting its parameter to false, which aligns the element at the bottom of the viewport:Lastly you can use JQuery, with
animate()
: