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.
