0

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>
mistenkt
  • 2,302
  • 3
  • 15
  • 19

2 Answers2

2

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();
0

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.

Parivalavan
  • 11
  • 1
  • 2