4

I'm building a WYISWYG editor with an iframe with designMode = 'on'.

The problem is that I can't use any event on the iframe in Firefox and Opera (IE untested), for example I would like to track the onkeyup event:

document.getElementById("myFrame").onkeyup = function(){
    doSomething...
}

But doesn't works in the parent window.

I tried in the iframe too with this:

top.frames[0].onkeyup = function(){
        doSomething...
}

and all kind of stuff like these:

top.document.frames[0].onkeyup
top.frames["myFrame"].onkeyup
top.frames[0].document.onkeyup

But none of them wants to work so at the end turned out that even window.onclick doesn't works, so now I'm a bit confused...

What's the solution for this?

EDIT

The problem seems to be with document.designMode = "on" in the iframe

2
  • Is your iframe on a different domain? Can you post a JSFiddle.net example? Commented Feb 6, 2011 at 17:13
  • No it's not on a different domain, It has a source but both files are on localhost. How should I post an example there if there is no way to add another HTML file as the iframe source? Commented Feb 6, 2011 at 17:17

1 Answer 1

11

I would suggest catching the event on the iframe's Document, and in Firefox at least you need to do this using addEventListener() rather than onkeyup. The following will work in all major browsers:

var iframe = document.getElementById("myFrame");
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

function handleIframeKeyUp(evt) {
    alert("Key up!");
}

if (typeof iframeDoc.addEventListener != "undefined") {
    iframeDoc.addEventListener("keyup", handleIframeKeyUp, false);
} else if (typeof iframeDoc.attachEvent != "undefined") {
    iframeDoc.attachEvent("onkeyup", handleIframeKeyUp);
}
Sign up to request clarification or add additional context in comments.

4 Comments

This works with click, keyup etc but not focus or blur. Any ideas?
@Nick: focus and blur don't bubble and don't fire on the document. It may work on the iframe element itself or its window (iframe.contentWindow).
I found that it worked in Firefox, but Safari and Chrome wouldn't respond to blur/focus events on the iframe element itself, I had to bind those events to the body element within the iframe.
Thanks Tim! Had the exact issue, trying to catch the event on the document, which works fine in Chrome. Now I just use $($editor.contentWindow).blur(function () { // code goes here }); for all browsers

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.