I shall open a dialog which contains an iframe, then set the focus inside the iframe once the dialog is opened.
Currently, I try to get the focus on the iframe when the content is loaded:
<iframe src="../credits.html" onload="this.contentWindow.focus()"></iframe>
It works fine for all browsers except for Firefox, and I don't understand why.
Can someone tell me why? Thanks
Contents of iframe works well in chrome but not in firefox.
Firefox seems not to have contentWindow property, you should use contentDocument
Update:
After a small debate I came up with a better solution:
<html>
<head>
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(function() {
$("#xframe").bind("load", function(){
$(this).contents().find("#xa").focus();
});
});
</script>
</head>
<body>
<iframe id="xframe" src="./y.html"></iframe>
</body>
</html>
In this example, I assume that there's a input field inside y.html that has a "xa" id. It worked both on Chrome and Firefox.
Old answer
Even better you should use jquery, something like:
<html>
<head>
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#xframe").focus();
});
</script>
</head>
<body>
<iframe id="xframe" src="./y.html"></iframe>
</body>
</html>
Of course you could do some extra check to see if the iframe is ready.
More info can be found here http://www.w3schools.com/jsref/prop_frame_contentwindow.asp
Try do this using jquery
// focus an input in iframe
$('#xframe').contents().find('input').get(0).focus()
// or simply iframe window
var iframe= $('#xframe')[0];
var iframewindow= iframe.contentWindow? iframe.contentWindow : iframe.contentDocument.defaultView;
iframewindow.focus()
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