11 Aug

add a key handler to CodePress

as part of KFM 1.1, I was asked to add a few key bindings to some parts. The trickier part was to treat the Esc key as a “Close” request in CodePress embedded text editors.

It was tricky, as I did not want to directly hack CodePress – I inevitably forget the hack when it comes to time for an upgrade, and overwrite my hack with the latest new copy.

So, the hack is slightly different. Instead, I have a setTimeout loop running in the parent window, testing to see if the CodePress window has finished loading yet. When it has, a keypress event function is manually inserted into the CodePress window, testing for the Esc key.

Code for the CodePress creation (I’m using MooTools in the parent window):

function kfm_textfile_createEditor(){
    CodePress.run();
    if($("kfm_tooltip"))$("kfm_tooltip").remove();
    kfm_textfile_attachKeyBinding();
}

Now, start the onload loop – note that I’m using browser-based event attaching here, as CodePress does not use mootools:

function kfm_textfile_attachKeyBinding(){
    if(!codepress.editor||!codepress.editor.body)return setTimeout('kfm_textfile_attachKeyBinding();',1);
    var doc=codepress.contentWindow.document;
    if(doc.attachEvent)doc.attachEvent('onkeypress',kfm_textfile_keybinding);
    else doc.addEventListener('keypress',kfm_textfile_keybinding,false);
}

And finally, the test for the esc key

function kfm_textfile_keybinding(e){
    e=new Event(e);
    if(e.code!=27)return;
    e.stopPropagation();
    kfm_textfile_close();
}

One thought on “add a key handler to CodePress

Comments are closed.