focus() to input without scrolling
Here's a complete solution:
var cursorFocus = function(elem) {
var x = window.scrollX, y = window.scrollY;
elem.focus();
window.scrollTo(x, y);
}
cursorFocus(document.getElementById('search-terms'));
There is a new WHATWG standard which allows you you to pass an object to focus()
which specifies that you want to prevent the browser from scrolling the element into view:
const element = document.getElementById('search-terms')
element.focus({
preventScroll: true
});
It has been supported since Chrome 64 and Edge Insider Preview build 17046, and should be landing in Firefox 68 – a support matrix is available on web-platform-tests here.