Stephen Jenkins
Stephen Jenkins

Reputation: 1836

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/

Upvotes: 9

Views: 27659

Answers (3)

Jordan Robert Dobson
Jordan Robert Dobson

Reputation: 81

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.

Upvotes: 8

Chamika Sandamal
Chamika Sandamal

Reputation: 24302

Try to add the javascript code soon after the input element, so it will execute before the page load complete. In your case autofocus attribute is set to the element but focusing the element which has autofocus by browser is already done. so you setting the value after browser set the focus. when browser trying to set it no attribute is there. try like following code

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

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

If you need to do it on button click or something, you need to do it in JavaScript. setting an attribute doesn't mean browser is going to execute it at anytime.

Upvotes: 2

John b
John b

Reputation: 1398

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

Upvotes: 10

Related Questions