I have a search input text which I'd like to apply a focus()
when loading the page, the problem is that the focus
function automatically does a scroll to this field. Any solution to disable this scroll?
<input id="search_terms" type="text" />
<script>
document.getelementbyId('search-terms').focus();
</script>
As of today, the preferred way to set the focus on an element upon page load is using the
autofocus
attribute. This does not involve any scrolling.The
autofocus
attrubute is part of the HTML5 standard and is supported by all major browsers, with the only notable exception of Internet Explorer 9 or earlier.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:It is currently supported in Chrome 64 and Edge Insider Preview build 17046.
If you are using jQuery, you can also do this:
and then
A bit modified version that supports more browsers (incl. IE9)
The answers here do not take care of scrolling on the whole hierarchy, but the main scrollbars only. This answer will take care of everything:
Here's a complete solution: