tags:

views:

73

answers:

2

Apologize if this is answered already. Went through some of the related questions and google, but ultimately failed to see why this isn't working.

My code is as follows

<iframe id="editor"></iframe>

editorWindow = document.getElementById('editor').contentWindow;
isCtrlDown = false;

function loadEditor()
{
    editorWindow.document.designMode = "on";
    editorWindow.document.onkeyup = function(e) {
        if (e.which == 91) isCtrlDown = false;
    }
    editorWindow.document.onkeydown = handleKeyDown;
}

function handleKeyDown(e)
{
    if (e.which == 91) isCtrlDown = true;
    if (e.which == 66 && isCtrlDown) editFont('bold');
    if (e.which == 73 && isCtrlDown) editFont('italic');
}

function editFont(a,b)
{
    editorWindow.document.execCommand(a,false,b);
    editorWindow.focus();
}

This code works perfectly in Chrome, but the keyboard shortcuts do not work in Firefox. In fact, in Firefox it does not seem to register the events for keyup/keydown at all.

Am I doing something grossly wrong here that is mucking up Firefox?

A: 

Try using:

editorWindow = document.getElementById('editor').frameElement;

I'm not sure this will solve the issue, it may also be:

editorWindow = document.getElementById('editor').contentDocument;

Or even possibly:

editorWindow = document.getElementById('editor').frameElement.contentDocument;

One thing you can do is put the entire string in a try statement to catch any errors and see if the content is being grabbed from within the iframe.

try { editorWindow = document.getElementById('editor').contentWindow; } catch(e) { alert(e) };

The only other thought I have is that you're typing into a textbox which is within an iframe, and you may possibly have to add the onkeydown event to that specific item, such as:

var editorWindow = document.getElementById('editor').contentDocument;
var textbox = editorWindow.getElementById('my_textbox');

function loadEditor()
{
editorWindow.document.designMode = "on";
textbox.onkeydown = function(e) {
    alert('hello there');
}
}

I hope one of these is the solution. I often find when it comes to cross-platform functionality it often boils down to a little trial and error.

Good Luck!

Alex
Did this work at all for you?
Alex
Unfortunately not. Might just be something weird with Firefox's implementation or something special for Chromes. I ended up using AddEventListener like someone suggested above. Thanks for your help though.
kkshin
+1  A: 

For editable documents, you need to use addEventListener to attach key events rather than DOM0 event handler properties:

editorWindow.document.addEventListener("keydown", handleKeyDown false);

If you care about IE 6-8, you'll need to test for the existence addEventListener and add the attachEvent equivalent if it's missing.

Tim Down
That works perfectly! Would rep you if I could :)
kkshin
Thanks. You can accept an answer by clicking the green tick to the left of it.
Tim Down