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>
Yes - this is possible. In order to do it, you need to assign a tabindex...
focus() Javascript focus() methods helps to highlight a HTML form element. It sets the element as an active element in the current document. In current documentation, focus can be applied to only one single element.
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.
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.
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With