0

I have an iframe that has its own application. I want to be able to focus a target outside the iframe but so far it's not recognizing it. On the page itself, it works, but once inside the iframe ( text area ), I want to shortcut out of the iframe. The function works inside the iframe ( console.log works at least ) but not the actual focus event. I tried to focus on the document first and then have it run the action, but it is not focusing outside the iframe. I have to have the function in the application so that it recognizes it.

https://jsfiddle.net/5ufc4koc/

<div class="field">
    <a href="#">Testing</a>
    <iframe>
        <div>Text text text
        </div>
    </iframe>
</div>

App.outside = function () {
    $(document).focus();
    $(document).on('keydown', function (e) {
        if (e.which === 113) {
            $('.field:first a').focus();
            console.log('testing');
        }
    });
};
Keith
  • 4,059
  • 2
  • 32
  • 56
  • `$(document)` isn't focusable, but you can read the duplicate that I will mark – Marcos Pérez Gude Sep 29 '16 at 15:47
  • Possible duplicate of [Is there any way in JavaScript to focus the document (content area)?](http://stackoverflow.com/questions/6976486/is-there-any-way-in-javascript-to-focus-the-document-content-area) – Marcos Pérez Gude Sep 29 '16 at 15:47
  • not very clear which document you are trying to target for `keydown`. Iframe has it's own document and anything you do on top of the iframe won't trigger in parent document – charlietfl Sep 29 '16 at 15:48
  • yeah i want to get back to the parent document to trigger the focus – Keith Sep 29 '16 at 15:50
  • use `$('#iframeId').contents()` to access inside iframe ... after it loads and assuming the iframe is on same domain – charlietfl Sep 29 '16 at 15:53
  • I don't need to access the contents to access the contents inside the iframe, I need to be able to access the contents outside iframe once the cursor is within the iframe. Currently it is not – Keith Sep 29 '16 at 15:54
  • Your fiddle is irrelevant. ` – Marcos Pérez Gude Sep 29 '16 at 16:02
  • i figured it out, have to use window.parent.function() – Keith Sep 29 '16 at 16:07

1 Answers1

0

Place within the iframe another jquery/java script-- focusing on the "parent.window.document".

$(document).ready(function(){

   var form = parent.window.document.querySelector('.field');
var toBeFocusedOn = parent.window.document.getElementById("#whateverIdOnMainPage");
$( document ).on( 'keydown', function ( e ) {
  if ( e.keyCode === 133 ) { // key code  '27 is ESC'
    
    toBeFocusedOn.focus();     
  }
});
  });
Jim Garbe
  • 1
  • 2