Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting 'autofocus' attribute with JavaScript not working

I am writing a small plugin, and the plugin will encapsulate an autofocus setting, but when I add the attribute dynamically with JavaScript, it doesn't autofocus the page, which is weird. Is there anyway around this?

HTML:

<input type="text">

JS:

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

Without doing:

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

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

like image 295
Stephen Jenkins Avatar asked May 28 '13 14:05

Stephen Jenkins


People also ask

Can we implement autofocus from JavaScript?

JavaScript autofocusers (as given in the other answers here) will work but can be annoying for some users. For example, if you focus a different field while a page is still loading, the JavaScript may "help" you by moving the focus and making you type in the wrong field.

Why autofocus is not working in react?

If you render your React component into a detached element, React will call focus() too soon. This will result in the input not focusing when your React tree gets added to the DOM.

Which element does not support autofocus attribute?

8. Which of the following element does not support autofocus attribute? <base> does not support autofocus attribute.

Is autofocus attribute always set focus on first input field?

The first input or textarea in source order that has the autofocus attribute will be focused on page load. In browsers without autofocus support, no fields will be focused on page load, unless otherwise given focus with JavaScript.


2 Answers

The best approach seems to be this:

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

This post might help explain why to use a reflected property: https://stackoverflow.com/a/18770417/3920924

However it seems you need to apply it near the document load. Otherwise it doesn't seem to fire. I think that's 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's defined to work as soon as the page is loaded. I haven't seen anything else that says it can be called later in time. Every time I've tried to fire it later with like a setTimeout of 3 seconds it never focuses the field.

like image 110
Jordan Robert Dobson Avatar answered Oct 19 '22 23:10

Jordan Robert Dobson


Try something like this

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

Edit

If you want to HTML 5 standard you should make the 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

like image 36
John b Avatar answered Oct 19 '22 23:10

John b