Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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");

like image 709
Ian Smith Avatar asked Oct 12 '13 16:10

Ian Smith


People also ask

How do I add focus to textarea?

Answer: Use the jQuery . focus() method You can simply use the jQuery . focus() method to set the focus on the first input box or textarea inside the Bootstrap modal when it is loaded upon activation.

What is focus function in JavaScript?

JavaScript | Focus()It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc. It is supported by all the browsers. Syntax: HTMLElementObject.focus()

Why focus is not working jQuery?

The reason that's not working is simply because it's not stealing focus from the dev console. If you run the following code in your console and then quickly click in your browser window after, you will see it focus the search box: setTimeout(function() { $('input[name="q"]'). focus() }, 3000);


2 Answers

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.

like image 145
Hasib Tarafder Avatar answered Nov 02 '22 13:11

Hasib Tarafder


You can also use setTimeout irrespective of the event.

setTimeout(function() {
    document.getElementById("elementId").focus();
}, 0);
like image 44
Ishan Liyanage Avatar answered Nov 02 '22 15:11

Ishan Liyanage