I have a JavaScript code that makes sure a text box is selected when my page loads. I have included my code below:
<!doctype html>
<html>
<head>
<script type="text/javascript">
function box(query){
document.getElementById('query').focus();
}
</script>
</head>
<body onload="box('query');">
<input id="query">
</body>
</html>
My question is; How can I make this script work without onload in my body tag?
I hope you can understand what I am trying to describe.
Thanks in advance, Callum
Place it inside the closing </body>
tag, so that the query
element has loaded before it runs:
<!doctype html>
<html>
<head>
</head>
<body>
<input id="query">
<script type="text/javascript">
function box(query){
document.getElementById('query').focus();
}
box('query');
</script>
</body>
</html>
Put a script tag at the bottom of the page, before the body tag. That way the DOM will (probably) have loaded and it will run:
<script type="text/javascript">
runmyfunction(); </script>
By the time the browser gets there the DOM should have loaded.
It might not have loaded, though. You could use something like Jquery to run your script when the page/dom has loaded.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.