4

I would like to hook the keydown event in the TinyMCE Editor on the edit post admin page. I managed to hook the HTML content editor using the following code:

jQuery('#content').keydown(function(){
    alert("keydown")
});

Here is my failed attempt at hooking the TinyMCE editor. The problem is that the editor hasn't been init yet so the variable ed is undefined.

var ed = tinyMCE.getInstanceById('tinymce');
ed.onChange.add(function(ed, l) {
    alert("keydown");
});

Any help would be much appreciated!

  • 1
    Your custom TinyMCE code should go inside a TinyMCE plugin, check some of the related links(to the right of this page) for examples of how this is done. – t31os Jul 26 '11 at 14:56
6

the TinyMCE Editor has its own keydown event handler and its hooked to a function on initiation so to do that you can create a tinymce plugin or use the wordpress initiation of it with tiny_mce_before_init hook like this:

add_filter( 'tiny_mce_before_init', 'wpse24113_tiny_mce_before_init' );
function wpse24113_tiny_mce_before_init( $initArray )
{
    $initArray['setup'] = <<<JS
[function(ed) {
    ed.onKeyDown.add(function(ed, e) {
        //your function goes here
        console.debug('Key down event: ' + e.keyCode);
    });

}][0]
JS;
    return $initArray;
}
  • Thank you! That's exactly what I wanted to do. The only stuff I could find was using the tinyMCE init to create new editors with event handling. Using tiny_mce_before_init worked perfectly. Thank you so much. – odie5533 Jul 26 '11 at 16:39
  • Glad I could help. – Bainternet Jul 26 '11 at 16:46
  • Glad I found this, it's exactly what I needed. Thanks. – David Gard Jul 12 '13 at 12:02
  • Thanks! I found this difficult to get going but did so without the <<<JS [ ... ][0] JS stuff. So just had the function in single quotes ['setup']= ' function(edtr){/*do stuff*/} '; The stuff in the script block was moved to a js function placed earlier on the page so that single quotes in it weren't terminating the string. Also, this needs to be added so that it occurs before tinymce is initialised or it won't have any affect. It's been a long process for this WP/tinymce/PHP noob! – wunth Aug 30 '16 at 18:37

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.