Search code examples
windowshtmlwindows-store-appsonkeydown

execCommand doesn't fire when called from keydown event in Windows Store apps


I'm writing a windows store app (HTML) that includes some simple rich-text editing. I can apply bold to the currently selected using a button which fires document.execCommand("bold",false,null);

However when I bind this to a keydown event like CTRL+B, nothing happens. Here's my keydown code.

document.addEventListener("keydown", catchShortCuts, false);

function catchShortCuts(e) {
    if (e.ctrlKey) {
        if (e.keyCode == 66) // b
            document.execCommand('bold', true, null);
        }
    }
}

I know my keydown code works fine because if I replace the document.execCommand with another line of code it fires just fine when I press CTRL+B. It seems like execCommand has a problem with the keydown event?


Solution

  • Turns out that it works fine if you use keypress instead of keydown. Just in case anyone else has the same issue, that's a workaround. Still not sure why onkeydown doesn't work though.

    Working code:

    document.addEventListener("keypress", catchShortCuts, false);
    
    function catchShortCuts(e) {
        if (e.ctrlKey) {
            if (e.keyCode == 66) // b
                document.execCommand('bold', true, null);
            }
        }
    }