Search code examples
selectformatstylestinymce

tinymce apply style to whole line like heading, paragraph


I am searching for a way to apply style to whole line like the default behavior of the heading or paragraph in tinymce editor.

More clearly, there is strange behaviour when we set the heading 1 or paragraph, the whole line of cursor get applied the style automatically without highlighting(blue) the text with cursor.

Any way to use this same behaviour to apply style when i use a custom shortcut on tinymce.

editor.addShortcut(
      'meta+alt+u', 'Add yellow highlight to selected text.', function () {
    tinymce.activeEditor.execCommand('FontSize', 0, '24px');
        
    });

this works only on selected text not to full line.


Solution

  • The difference is in what the format applies to within the editor.

    Some styles are "inline" and you will see the editor wrap the selection with a <span> tag to apply the formatting. Other behaviors (e.g. make something a heading) applies to the entire block level element (e.g. <p> or <div>).

    The style_formats configuration option provides you a way to designate how to apply the style. Here is a TinyMCE Fiddle that shows how to add both block and inline level styles:

    http://fiddle.tinymce.com/Cthaab

    The key configuration setting is:

    style_formats: [
      {title: 'Red text - applies inline', inline: 'span', styles: {color: '#ff0000'}},
      {title: 'Red paragraph - applies to block', block: 'p', styles: {color: '#ff0000'}},
    ]
    

    You will see that you can control how the style applies and to what tag. The documentation better covers all the options for the style_formats option: https://www.tiny.cloud/docs/configure/editor-appearance/#style_formats

    The fiddle also logs to the browser's console the actual command that TinyMCE is executing when these two examples are applied. You can certainly use the same API to apply styles yourself but as the editor already has a UI to do this it would seem easier to use the existing UI.