Setting the autofocus attribute with broken JavaScript

I am writing a small plugin and the plugin encapsulates the autofocus setting, but when I dynamically add an attribute using JavaScript, it does not autofocus the page, which is strange. Anyway, around?

HTML:

<input type="text"> 

JS:

 document.querySelector('input').setAttribute('autofocus', 'autofocus'); 

Without execution:

 document.querySelector('input').setAttribute('autofocus', 'autofocus').focus(); 

jSFiddle: http://jsfiddle.net/wPUNN/

+4
source share
3 answers

The best approach is as follows:

 document.querySelector('input').autofocus = true; 

This post may help explain why to use the reflected property: fooobar.com/questions/112653 / ...

However, it seems you need to apply it next to the loading of the document. Otherwise, it does not seem to work. I think because here ( http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#autofocusing-a-form-control:-the-autofocus-attribute:the- dialog-element ) it is defined to work as soon as the page loads. I have not seen anything else that says that it can be called later. Every time I tried to run it later, as using setTimeout of 3 seconds, it never focuses the field.

+2
source

Try something like this

 document.querySelector('input').focus() 

Edit

If you want to use the HTML 5 standard, you should make HTML look something like this.

 <input type="text" autofocus> 

http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#autofocusing-a-form-control:-the-autofocus-attribute

+1
source

Try adding javascript soon after the input element so that it runs until the page loads. In your case, the autofocus attribute is set to this element, but the focus on the element that autofocus has on the browser is already done. therefore, you set the value after the browser has set focus. when the browser does not try to set it without an attribute. try the following code

 <input type="text"> <script> document.querySelector('input').setAttribute('autofocus', 'autofocus'); </script> 

http://jsbin.com/yatugaxe/1/

If you need to do this with the click of a button or something else, you need to do it in JavaScript. setting an attribute does not mean that the browser will execute it at any time.

0
source

Source: https://habr.com/ru/post/1483172/


All Articles