ChatGPT解决这个技术问题 Extra ChatGPT

Scroll back to the top of scrollable div

<div id="containerDiv"></div>
#containerDiv {
  position: absolute;
  top: 0px;
  width: 400px;
  height: 100%;
  padding: 5px;
  font-size: .875em;
  overflow-y: scroll;
}
document.getElementById("containerDiv").innerHTML = variableLongText;

How to reset the scroll position back to top of container div the next time?


a
andrewb
var myDiv = document.getElementById('containerDiv');
myDiv.innerHTML = variableLongText;
myDiv.scrollTop = 0;

See the scrollTop attribute.


Tried but it didn't work. When a variableLongtext is loaded in the container div and am looking at the middle of it, then swipe to the new variableLongtext, it will show up in container, but we will not be looking at the top of the it, it will already be scrolled down a bit.
@s12345 You'd better make a reproducible test case showing us your problem (e.g. on jsfiddle.net) and say what OS/browser/version you're experiencing this on.
Sorry my mistake.. it works! Got confused with two similar divs.
No jQuery required: document.getElementById('my_element_id_to_scroll').scrollTo(0,0);
M
Mahmoud Ibrahim

Another way to do it with a smooth animation is like this

$("#containerDiv").animate({ scrollTop: 0 }, "fast");

Works well, but please don't use slow, it's so... slow!
Instead of passing slow as the second argument. You can pass in an integer which would be the number of milliseconds for the animation to complete.
Changed it to fast :)
Best answer! Thanks!
This works fine if you are using jquery. If you are using angular typescript (plain javascript) this will not work. how can you achieve this with plain javascript.
S
Sunnyside Productions

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);

Is that a jQuery thing? Because I get scrollTop is not a function.
R
Rajat

This worked for me :

document.getElementById('yourDivID').scrollIntoView();

This is my preferred solution. For smooth transition, add this: document.getElementById("yourDivID").scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"})
Also, note that scollIntoView only works if you call it on the element which is to be scrolled. In other words, don't call it on the element you want to scroll to, call it on the element you want to scroll.
B
Brian Burns

scrollTo

window.scrollTo(0, 0);

is the ultimate solution for scrolling the windows to the top - the best part is that it does not require any id selector and even if we use the IFRAME structure it will work extremely well.

The scrollTo() method scrolls the document to the specified coordinates. window.scrollTo(xpos, ypos); xpos Number Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels ypos Number Required. The coordinate to scroll to, along the y-axis (vertical), in pixels

jQuery

Another option to do the same is using jQuery and it will give a smoother look for the same

$('html,body').animate({scrollTop: 0}, 100);

where 0 after the scrollTop specifies the vertical scrollbar position in the pixel and second parameter is an optional parameter which shows the time in microseconds to complete the task.


what if we only want to scroll an internal div to the top? This will ultimately not work.
Elements also have the .scrollTo method, you can do document.getElementById('scroller').scrollTo(0,0)
J
Jakub Muda

For those who still can't make this work, make sure that the overflowed element is displayed before using the jQuery function.

Example:

$('#elem').show();
$('#elem').scrollTop(0);

Life saver! Was beginning to lose the will to live with scrollTop not working! had to put my scrollTop call in a setTimeout function.
I feel the same! I was working in a bootstrap modal dialog box. I had to setup an event for the modal that didn't reset the scrollbar until the modal had stopped animating. This is code I used: $('#add_modal').on('shown.bs.modal', function (e) { $('div.border').scrollTop(0); });
J
Jakub Muda

2020 UPDATE

You can use .scroll() to easily scroll elements or window. It has a built-in smooth scroll effect so basically the code couldn't be simpler.

Standard properties:

var options = {
    top:       0,        // Number of pixels along the Y axis to scroll the window or element
    left:      0,        // Number of pixels along the X axis to scroll the window or element.
    behavior:  'smooth'  // ('smooth'|'auto') - animate smoothly, or move in a single jump
}

DOCS: https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll

SEE ALSO: .scrollIntoView() https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

DEMO:

document.getElementById('btn').addEventListener('click',function(){ document.getElementById('container').scroll({top:0,behavior:'smooth'}); }); /*DEMO*/ #container{ width:300px; max-height:300px; padding:1rem; margin-left:auto; margin-right:auto; background-color:#222; color:#ccc; text-align:justify; overflow-y:auto; } #btn{ width:100%; margin-top:1rem; }

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


A
Ashwin

If you want to scroll with a smooth transition, you could use this!

(Vanilla JS)

const tabScroll = document.getElementById("tabScroll");
window.scrollTo({
  'behavior': 'smooth',
  'left': 0,
  'top': tabScroll.offsetTop - 80
});

If your target users are Chrome and Firefox, then this is good! But unfortunately this method isn’t supported well enough on all browsers. Check Here

Hope this helps!!


M
Mahsan Nourani

When getting element by class name, don't forget the return value is an array; Hence this code:

document.getElementByClassName("dropdown-menu").scrollTop = 0

Would not work. Use code below instead.

document.getElementByClassName("dropdown-menu")[0].scrollTop = 0

I figured other people might encounter a similar problem as I did; so this should do the trick.


A
AlexTR

For me the scrollTop way did not work, but I found other:

element.style.display = 'none';
setTimeout(function() { element.style.display = 'block' }, 100);

Did not check the minimum time for reliable css rendering though, 100ms might be overkill.


I
Irv Lennert

As per François Noël's answer "For those who still can't make this work, make sure that the overflowed element is displayed before using the jQuery function."

I had been working in a bootstrap modal that I repeatedly bring up with account permissions in a div that overflows on the y dimension. My problem was, I was trying to use the jquery .scrollTop(0) function and it would not work no matter how I tried to do it. I had to setup an event for the modal that didn't reset the scrollbar until the modal had stopped animating. The code that finally worked for me is here:

    $('#add-modal').on('shown.bs.modal', function (e) {
        $('div.border').scrollTop(0);
    });

F
Fred K

This is the only way it worked for me, with smooth scrolling transition:

  $('html, body').animate({
    scrollTop: $('#containerDiv').offset().top,
  }, 250);

c
csandreas1

The ID Should have the id of the corresponding div that has the overflow css property.

document.querySelector('#YOUR_OVERFLOWED_DIV').scrollTop = 0;


R
Ruben

If the html content overflow a single viewport, this worked for me using only javascript:

document.getElementsByTagName('body')[0].scrollTop = 0;

Regards,


A
Amir shah

these two codes worked for me like a charm this first will take to scroll to the top of the page but if you want to scroll to some specific div use the second one with your div id.

$('body, html, #containerDiv').scrollTop(0);
document.getElementById('yourDivID').scrollIntoView();

If you want to scroll to by a class name use the below code

var $container = $("html,body");
var $scrollTo = $('.main-content');

$container.animate({scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop(), scrollLeft: 0},300);