9

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/

2
  • Why don't you want to .focus() ? Commented May 28, 2013 at 14:25
  • Because that's not HTML5, that's using the JavaScript to emulate it. There is an issue of setting the attribute, to having it there natively while the HTML is rendering. Commented May 28, 2013 at 14:27

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I was trying to set the autofocus attribute, but I had to do this instead
9

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.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.