Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change focus out of IFrame

I have an IFrame with some buttons in it. When the buttons are clicked, the parent DOM is manipulated (it's all in the same domain, so don't worry about the same-origin policy).

Since the user clicked on a button, the focus goes to the IFrame. However, I'd like to move the focus back to the parent document (mostly due to this FireFox problem).

How can I do this?

Edit: I've created a js-fiddle that shows the problem. While focus() seems to work if you call it on parent form elements, it doesn't work in general. As you can see from the js-fiddle there are no form elements in my parent document.

like image 969
paleozogt Avatar asked May 08 '12 15:05

paleozogt


1 Answers

If you want to set the focus back to the outer window from inside the iframe, focussing the outer window itself is unlikely to give any visual feedback to the user, so it is better to focus a known form element in the outer page.

You can do this as follows:

outer.html

<html>
  <head>
    <title>Outer</title>
  </head>
  <body>
    <iframe id="iframe" src="inner.html">
    </iframe>
  </body>
</html>

inner.html

<html>
  <head>
    <title>Inner</title>
  </head>
  <body>
    <form id="innerForm">
      <input type="button" id="innerButton" value="Inner button" />
    </form>
  </body>
  <script type="text/javascript">
    // When we click the inner button...
    document.getElementById('innerButton').addEventListener('click', function() {
      /*
       * Do whatever you need to do here
       */

      // Focus the parent
      parent.focus();
    });
  </script>
</html>
like image 193
Jim O'Brien Avatar answered Oct 22 '22 00:10

Jim O'Brien