OsiOs OsiOs - 3 years ago 167
CSS Question

Scrolling down in a particular div instead in the window itself in vanilla JS

In facebook.com there's your conversations page.

In desktop view, you can scroll down this div to see all your messages.

The div's class is

.uiScrollableAreaBody
.

I desire to go into the conversations page, execute in console the relevant code, and start to scroll down until the possible end, until I'll be scrolled down maximally (after all scroll down "stops" or "stations" have been passed by my script).

That's instead me need to site there and scroll down, "stop after stop" or "station after station" (sorry or the terminology, I know nothing better than these terms to describe it).

Here's one of the codes I tried to achieve it automatically:

document.querySelector(".uiScrollableAreaBody").scrollHeight;
// Outputted: 1398.


And:

document.querySelector(".uiScrollableAreaBody").scrollTop=100;
// Outputted: 100.


Do you know how to do so in vanilla JS?

BTW, I just give facebook.com's conversations page as an example - I call no one to scrap that site or any other site.

Answer Source

I think by your "stop after stop" or "station after station" terminology you are meaning their infinite scroll loading system.

And yes you had the right idea, setting scrollTop will trigger a scroll event which seems to do a load more request if needed.

You simply were targeting the wrong element. The element that needs it's scrollTop property set is uiScrollableAreaWrap

document.querySelector(".uiScrollableAreaWrap").scrollTop=100;

As for making it exhaust the infinite scroll, you can setup a MutationObserver to watch for additions into the content area and when it does, do the next scroll.

let contentScroller = document.querySelector(".uiScrollableAreaWrap");
let observer = new MutationObserver(mutations => {
  //In the case of FB message window you scroll up to load more
  //change this to the scrollHeight value if needing to scroll down.
  if(contentScroller.scrollTop > 0) {
    contentScroller.scrollTop = 0;
  }
});
observer.observe(contentScroller, {childList:true, subtree:true});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download