focus() to input without scrolling

Solution 1:

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.

Solution 2:

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'));

Solution 3:

If you are using jQuery, you can also do this:

$.fn.focusWithoutScrolling = function(){
  var x = window.scrollX, y = window.scrollY;
  this.focus();
  window.scrollTo(x, y);
};

and then

$('#search_terms').focusWithoutScrolling();