How do you set the focus of a TinyMCE textarea element?

Viewed 61677

I'm using TinyMCE for a textarea on a page but it doesn't play nice in the tabbing order of the other elements.

I can use the following code to capture when I tab out of the first element:

$('#title').live('keypress', function (e) {
   if(e.keyCode == 9) {
       alert('tabbed out');
   }
});

How can I set the focus to a TinyMCE editor?

13 Answers

Looks like for TinyMCE 4 a few of these solutions no longer work.

// Doesn't seem to work on TinyMCE 4

tinymce.execCommand('mceFocus',false,'id_of_textarea'); 

// Didn't work

$("id_of_textarea").tinymce().focus();

tinyMCE.activeEditor.focus();

What works for me

// Works great in Chrome, but not at all in Firefox

tinyMCE.init({
    //...
    auto_focus : "id_of_textarea"
});

// Add this so Firefox also works

init_instance_callback : "customInitInstanceForTinyMce", // property to add into tinyMCE.init()

function customInitInstanceForTinyMce() {
    setTimeout(function () {                         // you may not need the timeout
        tinyMCE.get('Description').focus();
    }, 500);
}

This should pass focus to the TinyMCE textarea:

$("#id_of_tinyMCE_area").focus();

TinyMCE 4.7.4

None of the above worked for me, subscribing to TinyMCEs init event did work:

const elTinyMce = tinyMCE.get('your_textarea_id');
// (optional) This is not necessary.
// I do this because I may have multiple tinymce elements on my page
tinyMCE.setActive(elTinyMce);
elTinyMce.on('init', function () {
    // Set the focus
    elTinyMce.focus();
    // (optional) Select the content
    elTinyMce.selection.select(
        elTinyMce.getBody(),
        true
    );
    // (optional) Collapse the selection to start or end of range
    elTinyMce.selection.collapse(false);
});

Note: focusing on elements doesn't always work if you have the browsers developer tools open. You may be forcing the focus away from the page because a browser can only have one focus. This solution for example doesn't work either if you have developer tools open.

Related