Adding jquery listener for iframe content

StuartProgramming Blog

I have a solution that generates or downloads content, HTML formats it and pushes it into a dynamically generated iframe. Since the content is mostly forms, I need to know when the generated content is changed by a user.

In this application, the following works fine for the first generated form:

var iframe = element.find('iframe');
$(iframe.get(0).contentDocument).on('focusout', function (eventObject) {
   $(this).find("input,select,textarea").each(function () {
      //this in the previous statement is "document" because that's where the on.change is attached
      var currentInputElement = $(this);
      //do something with currentInputElement
   });
});

But for some reason, chrome and firefox would not attach the focusout event to the second and subsequent times that this code is called. Even though each time we get here, the iframe variable represents a new iframe object.

The solution turned out to be fairly simple. Add a .off before attempting to .on the ‘focusout’. While this is only required for the second and subsequent calls I added it to every call, and this code went to attaching as expected. I don’t know if this is because the javascript interpreter is confused about the state of that iframe variable, but next time I can’t get an event to attach, I’ll remember to try a:

$(iframe.get(0).contentDocument).off();
StuartAdding jquery listener for iframe content