Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

focus() to input without scrolling

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> 
like image 885
NoOneElse Avatar asked Feb 10 '11 21:02

NoOneElse


People also ask

Can we set focus on Div?

Yes - this is possible. In order to do it, you need to assign a tabindex...

Why is focus () Used?

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.

How do you set focus on input field?

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.


2 Answers

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.

like image 193
Josh Avatar answered Sep 18 '22 09:09

Josh


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')); 
like image 31
peterjwest Avatar answered Sep 18 '22 09:09

peterjwest