user3613129
user3613129

Reputation: 411

FocusOut event not being triggered on input box inside iframe

I have an input box inside an iframe. I have attached keypress, input and focusout event listeners on the input box like this :

$("iframe").contents().find('#testDiv').on('keypress input focusout', 'input', function(event) {
  alert(event.type);
});

Both keypress and input events are getting fired on the input box inside the iframe. However the focusout event is not getting fired on blur of the input box.

If the input box is not placed inside an iframe, the same syntax and event binding works fine. All the three events get fired on the input box that's not inside the iframe.

NOTE : I'm using event delegation because the content in the iframe is dynamic.

HTML Markup :

<iframe>
  <body>
  </body>
</iframe>
<div id="testDiv1">
  <input type="text" />
</div>

Javascript Code :

var $iframe = $("iframe");
var iframe = $iframe[0];
var doc = iframe.document;
var content = '<div id="testDiv"><input type="text" /></div>';
if (iframe.contentDocument) {
  doc = iframe.contentDocument;
} else if (iframe.contentWindow) {
  doc = iframe.contentWindow.document;
}
doc.open();
doc.writeln(content);
doc.close();

$("iframe").contents().find('#testDiv').on('keypress input focusout', 'input', function(event) {
  alert(event.type);
});

$('#testDiv1').on('keypress input focusout', 'input', function(event) {
  alert(event.type);
});

Here is a mockup of what I have tried : JSFiddle Demo

Please help!! I cannot move out the input box from the iframe.

Upvotes: 0

Views: 1405

Answers (1)

Raul Fernandez
Raul Fernandez

Reputation: 118

firstly, focusin and focusout are two events made by IE that supports bubbling up. However jquery simulate this events for the rest of the browsers.

Secondly, only trusted targets can be used for event delegation (see link: https://www.w3.org/TR/DOM-Level-3-Events/#event-type-focusout)

Even targeting the events to the input (see below), only blur and focus gets triggered (tested in Chrome).

$("iframe").contents().find('#testDiv input').on('focusout focusin focus blur', function(event) {
  alert('lol: ' + event.type);
});

So I guess, there's no straight answer for that. You may need to add some JS on the iframe content that can comunicate this event to the parent frame.

Upvotes: 2

Related Questions