We can use the scroll method of an element to scroll a scrollable div back to the top. Then we can add some content to the div and make the div scroll to the top when we click the button by writing: const div = document. querySelector('div') for (let i = 0; i < 100; i++) { const p = document.
onclick = function () { console. log('click') scrollTo(document. getElementById('container'), topPos-10, 600); } function scrollTo(element, to, duration) { var start = element. scrollTop, change = to - start, currentTime = 0, increment = 20; var animateScroll = function(){ currentTime += increment; var val = Math.
Method 1: Using window.scrollTo() The scrollTo() method of the window Interface can be used to scroll to a specified location on the page. It accepts 2 parameters the x and y coordinate of the page to scroll to. Passing both the parameters as 0 will scroll the page to the topmost and leftmost point.
The scrollTop() method sets or returns the vertical scrollbar position for the selected elements.
var myDiv = document.getElementById('containerDiv');
myDiv.innerHTML = variableLongText;
myDiv.scrollTop = 0;
See the scrollTop
attribute.
Another way to do it with a smooth animation is like this
$("#containerDiv").animate({ scrollTop: 0 }, "fast");
I tried the existing answers to this question, and none of them worked on Chrome for me. What did work was slightly different:
$('body, html, #containerDiv').scrollTop(0);
This worked for me :
document.getElementById('yourDivID').scrollIntoView();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With