2

I'm just looking to add a few buttons to the TinyMCE editor via a plugin. The buttons will have the exact same functionality as the bold/italic/strikethrough buttons, but will instead be for the HTML tags: <mark> and <ins>.

Can I re-use the code for these existing buttons and somehow extend it to change the html tag that is inserted?

I dug through the GitHub repo and could not find where this functionality is written. I'm hoping there is a simple API I can extend.

I found some command identifiers that look promising, like mceInsertContent that can insert something simple like an <hr />, but nothing for inserting tags around the selected text.

Timothy Fisher
  • 1,001
  • 10
  • 27

1 Answers1

4

You can create a simple toolbar button to wrap selected text with additional information by adding a small bit of code to your TinyMCE configuration.

Step 1: Define the custom button

The first thing you need to do is create a custom button (https://www.tiny.cloud/docs/ui-components/toolbarbuttons/). The code would look something like this:

editor.ui.registry.addButton('wrapselection', {
    text: 'Wrap Selection',
    onAction: function () {
        editor.insertContent("<mark>" + editor.selection.getContent() + "</mark>");
    }
});

You add this in the setup() function in your TinyMCE configuration.

Step 2: Add the button to the toolbar

Your TinyMCE configuration has a toolbar setting that controls what buttons appear on the toolbar. You need to add your new custom button to the toolbar:

toolbar: "wrapselection | code undo redo | bold italic | bullist numlist"

Here is a TinyMCE Fiddle that shows all of this in action: http://fiddle.tinymce.com/lQgaab/2

Michael Fromin
  • 13,131
  • 2
  • 20
  • 31
  • 2
    So I know that I could just as easily do the opposite to remove the tag if the text is highlighted and clicked again, but what if only a portion of the text inside the tag is selected. For example, if the HTML in the editor is: I want to unmark the word "this" ... and I highlight "this" and click the button, it should remove that word from the html tag, similar to how the "bold" button works. – Timothy Fisher Sep 09 '19 at 06:21