setting scrollTop for element

Hi, in older version of CM, I can set scroll position of the code mirror DOM by doing

let scrollEl = document.querySelector("")
scrollEl.scrollTop = some_position

But this same operation does not work in 6.0.
Any suggestion on how to fix this? Thanks.

That should still work.

1 Like

Any suggestion on how to fix this? Thanks.

The problem might be that cm-scroller is not a scrollable container because CodeMirror 6 can use a parent as a container. It can be solved by looking for a scrollable parent and scrolling it with something like that:

function findScrollContainer(node: HTMLElement) {
  for (let cur: any = node; cur; ) {
    if (cur.scrollHeight <= cur.clientHeight) {
      cur = cur.parentNode

    return cur
findScrollContainer(view.scrollDOM).scrollTop = ...

However, there is another problem that I faced: If the document is really big then I can not scroll past a certain height (probably because the document is not rendered there?)

The editor will render an empty element with the approximate height of the rest of the text. Can you reproduce this in a small example script?

I made a couple of experiments and this is what is going on:

  1. The scrollHeight measure synchronously after the editor is rendered differs from the actual scrollHeight when everything is settled
  2. The difference can be very big if lineWrapping is enabled

Because of this, if I try to scroll right after editor is rendered there is a big chance to get to the wrong position. For instance, in the following example, scroll height before and after some timeout is 8_000px vs 20_000px, and that’s why I can not scroll to 10_000px synchronously.

Is it a bug or a limitation of the way the things are rendered?

Using the scrollIntoView effect or giving the editor a moment to measure itself before you scroll might help (it does so in an animation frame callback). It doesn’t synchronously trigger a DOM layout when initialized, which means that at that point it won’t have an accurate representation of its height layout yet.

1 Like

Looks like manual scrolling with scrollTop can not scroll to a predictable position (even when doing in rAF or after timeout). As far as I understand it depends on whether the content was actually drawn above the scroll or it’s height was calculated approximately. In this case, scrollIntoView effect is the best option