How to Prevent Scroll Jumps When Using CodeMirror editor.focus() [Solved]

← Prev

If you're working with CodeMirror in a web-based "editor", you've likely run into the quirky side effect of scroll jumps when calling "editor.focus()". This seemingly small issue can disrupt user experience, especially in single-page apps or tight layouts. In this post, we’ll explore why this happens and how to prevent it, with practical solutions and sample code that smooth out your interface and keep your scroll position steady.

Solutions to Avoid the Scroll Jump

1. Use preventScroll: true in focus()

If you're using CodeMirror 6, it supports this in some contexts.

<script>
  editor.focus({ preventScroll: true });
</script>

Note: Please check the browser support for this feature.

2. Manually reset scroll after focus

You can store the scroll position before focusing and then restore it.

const scrollX = window.scrollX;
const scrollY = window.scrollY;

editor.focus();

// Restore scroll position.
window.scrollTo(scrollX, scrollY);

If your editor is inside another scrollable container, like a div, apply this to that container instead.

const container = document.querySelector('.editor-wrapper');
const scrollTop = container.scrollTop;

editor.focus();
container.scrollTop = scrollTop;

3. Use cursor setting only, skip focus()

Sometimes just placing the cursor is enough. For example,

editor.setCursor({ line: 0, ch: 0 });

This avoids triggering the scroll behavior caused by focus(), especially if the editor already has visual focus.

Disclaimer

🚀 I prefer using the third validation option in my JSON checker tool for the best results. It works fine and no need to set focus on editor.

← Previous