In Javascript setting a textarea with focus() does not work if called as a child window

Ian Smith picture Ian Smith · Oct 12, 2013 · Viewed 43k times · Source

I have a simple test page that sets the focus to a textarea on an oninit function. However the exact code fails to do this if the page is called as a child.

Putting alert box proves that the oninit function is being called but fails to put the focus in the textbox. Pressing reload though does then focus correctly.

So given that my code works perfectly when called on a main page, and also works in a child if reload is called, then why doesn't it work the first time?

<html>
<body onload="init()">
<script type="text/javascript">
function init()
{
    document.getElementById("message").focus();
}

</script>
<textarea id="message" rows=10 cols=40></textarea>
</body>
</html>

Nothing clever here as you can, just only doesn't work if the page is loaded by window.open("test2.html");

Answer

Hasib Hasan Arnab picture Hasib Hasan Arnab · Oct 12, 2013

which browser do you use? I check in firefox, chrome & IE. Your code runs perfect and focus on the textarea.

I create two file test1.html and test2.html in a same directory. In test1.html i insert the the follwing code..

<html>
<body>
<script type="text/javascript">
function init()
{
    window.open('test2.html');
}

</script>
<button onclick="init()">test</button>
</body>
</html>

And in test2.html..

<html>
<body onload="init()">
<script type="text/javascript">
function init()
{
    document.getElementById("message").focus();
}

</script>
<textarea id="message" rows=10 cols=40></textarea>
</body>
</html>

Than, I run the test1.html and click the button and test2.html appears with focus on the textarea.