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: 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.
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()
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);
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.
You can also use setTimeout irrespective of the event.
setTimeout(function() {
document.getElementById("elementId").focus();
}, 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With