mistenkt
mistenkt

Reputation: 2392

Tinymce toggle format, formats the button not the editor

So im having a little issue with tinymce4 api, iv created a custom format that i want to tigger with a button. However what happens is that when the button is clicked, the style is applied to the button instead of the actual contenteditable field..

tinymce.init({
    selector: '#editable',
    inline: true,
    menubar: false,
    toolbar:false,
    statusbar: false,
});

setTimeout(function(){
    tinymce.activeEditor.formatter.register('mycustomformat', {
   inline : 'span',
   styles: {color: 'red'}
 });
},200);

$('.js-toggleformat').on('click', function(e) {
    tinymce.activeEditor.formatter.apply('mycustomformat');
})

and the html:

<button class="js-toggleformat">Toggle</button>

<div id="editable" contenteditable="true"></div>

Upvotes: 0

Views: 1386

Answers (2)

user3159159
user3159159

Reputation: 21

Take a look at an example. The tinymce plugin "textcolor" uses a function "applyFormat" for applying the color. It looks like this:

function applyFormat(format, value) {
  editor.focus();
  editor.formatter.apply(format, {value: value});
  editor.nodeChanged();
}

Based on that, this should work in your case:

tinymce.activeEditor.focus();
tinymce.activeEditor.formatter.apply('mycustomformat');
tinymce.activeEditor.nodeChanged();

Upvotes: 2

Parivalavan
Parivalavan

Reputation: 11

I had similar issues. I guess your are using the inline edit option. When you click outside of the edit field the tinymce id deactivated.

You could solve this issue by two methods:

  1. You could customize the toolbar and add you required formats in the toolbar
  2. On tinymce blur event store the range using rangy library. On the button click first activate tinymce, restore the saved range and then use tinymce formatter to toggle the style

Hope this helps.

Upvotes: 0

Related Questions