1

I have a page containing an iframe in the center of the page and its cross domain iframe. When the page is loaded focus of the page is shifted to center of page containing iframe. I am trying to ensure focus is shifted to top of the page. Below solution works only in IE but not in chrome/Firefox.

Input control 'foo' is present at top portion of the page. Any idea? why it doesnt work I think chrome has problem with blur property.

<iframe width="1200" height="380" id="usageReport" src="https://google.com" frameborder="0" allowfullscreen="true"></iframe>
<script language="javascript" type="text/javascript">
window.onload = function() {            
         $('#foo').on('blur',function () { 
         var blurEl = $(this); 
         setTimeout(function() {
         blurEl.focus()
      }, 10);
      });

};
</script>
PRR
  • 87
  • 1
  • 9

1 Answers1

2

I think you are saying when the page loads, you want to focus on the input field.

Well, one thing that may work, I'm not sure with an iframe or what is going on there is simply add the HTML5 autofocus attribute onto the input.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/autofocus

To your code though, this part $('#foo').on('blur',function () { is a listener. So what your code is saying is this, When the user blurs from the input field, wait 10 miliseconds and then focus on the input field. I'm not sure that is what you want as anytime the user moves away from that field, it will try to get focus again. You simply want:

$(document).ready(function() {            
    setTimeout(function() {
        $('#foo').focus();
   }, 10);
});

My code simply says, when the page loads, focus on the input after 10 milliseconds. But really, the autofocus attribute would be better. This still may not work as the iframe may be capturing it after it loads too, so you really need to fire it after the iframe loads.

This is explained here: Capture iframe load complete event

Leeish
  • 5,203
  • 2
  • 17
  • 45