Input autofocus works on appending to document as well as onload

by steveukx

HTML

<input type="text" autofocus="true" />

CSS

input {
    background: transparent;
    display: block;
    outline: none;
    border: 1px solid #333;
    margin: 2px 4px;
}

input:focus { background: red; }
input:nth-child(1):focus { background: orange; }
input:nth-child(2):focus { background: blue; }
input:nth-child(3):focus { background: green; }
input:nth-child(4):focus { background: yellow; }
input:nth-child(5):focus { background: grey; }
input:nth-child(6):focus { background: black; }
input:nth-child(7):focus { background: cyan; }
input:nth-child(8):focus { background: magenta; }

JavaScript

var intervalId = setInterval((function() {
    var iterations = 0;
    return function() {
        var input = document.createElement('input');
        input.setAttribute('autofocus', true);
        input.setAttribute('type', 'text');
        
        document.body.appendChild(input);
        
        if(iterations++ > 5) clearInterval(intervalId);
    }
}()), 1000);