Note that there are some explanatory texts on larger screens.

plurals
  1. POCan using element.focus() just after an element's declaration in HTML be harmful?
    primarykey
    data
    text
    <p>I want to make a form in which I want to automatically give focus to a field. In the old days I learned to always wait doing any DOM manipulation till window.onload has fired, as the DOM might not be ready. Since JQuery the DOMContentReady event has grown famous, which fires (in compliant browsers) somewhat earlier than window.onload.</p> <p>That still gives a delay between the moment the field is shown and the moment it gets focus (by using document.getElementById("inputfield").focus() in window.onload or after DOMContentReady has been triggered). To minimize that delay, some people suggest using focus() directly after the element in your page, like:</p> <pre><code>&lt;form name="f"&gt; &lt;input id="q" autofocus&gt; &lt;script&gt; if (!("autofocus" in document.createElement("input"))) { document.getElementById("q").focus(); } &lt;/script&gt; &lt;input type="submit" value="Go"&gt; &lt;/form&gt; </code></pre> <p>(Example from <a href="http://diveintohtml5.info/forms.html#autofocus" rel="nofollow noreferrer">Dive Into HTML5</a>)</p> <p>Also, the Google Closure team advices this practice: "<a href="https://stackoverflow.com/questions/2024018/using-domcontentready-considered-anti-pattern-by-google">the preferred way is to use inline scripts as soon as possible</a>", like <a href="https://stackoverflow.com/questions/696102/should-focus-be-given-to-a-control-when-a-webpage-finishes-loading/698542#698542">another answer on SO</a> states.</p> <p>I don't want to debate whether this is bad practice or not (in general, I agree with the opinion that content and behaviour should be separated, preferably in separate files). My question is: <strong>can this be harmful?</strong> For instances, causing error messages in some browsers because the field might still not have been rendered properly (and don't forget mobile browsers). Any advice is appreciated.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload