Reputation: 3740
I faced a very interesting issue.
I'm trying to set the focus on a input field using Javascript (no jQuery, I tried that also but not worked) using window.onLoad
.
Just take a look at this fiddle : setFocusOnLoad
It's working fine in chrome browser but not in Firefox. Is there any issue in Firefox? How can I resolve it.
Edited:
Here is the code I copied in html file:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function onloadFocus(){
var name = document.getElementById('name');
// name.value='window.onload called';
name.focus();
}
window.onload=onloadFocus();
</script>
</head>
<body>
<div><input type='text' value='' id='name' name='name'></div>
</body>
</html>
Upvotes: 2
Views: 3252
Reputation: 11
I got the solution for it. If you want to focus in Firefox. Write the focus function at the starting of the script tag.
<script type="text/javascript">
document.getElementById('name').focus();
// rest of the code here.
</script>
Hope this will help you.
Upvotes: 0
Reputation: 23208
you should use window.onload=onloadFocus;
instead of window.onload=onloadFocus();
because in case of window.onload=onloadFocus();
onloadFocus will run immediately and at that time input field may not be available.
Upvotes: 0
Reputation: 117364
You must wrap the function-call into a function, otherwise it will be called immediately, not onLoad(the input is still unknown at this time):
window.onload=function(){onloadFocus();}
Upvotes: 0
Reputation: 6020
Try adding a slight delay:
function onloadFocus(){
setTimeout(function() {
document.getElementById('name').focus()
}, 10);
}
Upvotes: 6