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/
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.
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.
8. Which of the following element does not support autofocus attribute? <base> does not support autofocus attribute.
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.
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.
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
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