Creating custom Basic toolbar buttons
A basic button triggers its onAction
function when clicked.
Options
Name | Value | Requirement | Description |
---|---|---|---|
text |
string |
optional |
Text to display if no icon is found. |
icon |
string |
optional |
Name of the icon to be displayed. Must correspond to an icon: in the icon pack, in a custom icon pack, or added using the |
tooltip |
string |
optional |
Text for button tooltip. |
enabled |
boolean |
optional |
default: |
onSetup |
|
optional |
default: |
onAction |
|
required |
Function invoked when the button is clicked. |
API
Name | Value | Description |
---|---|---|
isEnabled |
|
Checks if the button is enabled. |
setEnabled |
|
Sets the button’s enabled state. |
NOTE: This feature is only available for TinyMCE 6.4 and later. |
||
setText |
|
Sets the text label to display. |
setIcon |
|
Sets the icon of the button. |
Basic button example and explanation
The following example adds two buttons to the toolbar:
The first button inserts "It’s my button!" into the editor when clicked. The second button is an example of how onSetup
works. This button inserts a time
element containing the current date into the editor using a toTimeHtml()
helper function - a simplified version of TinyMCE’s insertdatetime plugin.
In this example an icon from the insertdatetime
plugin is used to demonstrate how to use a registered icon. disabled
is set to true
so that the button is disabled when it is first rendered.
onSetup
is used to listen to the editor’s NodeChange
event to disable the button when the cursor is inside a time
element (or "node"). This ensures it is not possible to insert a time
element into another time
element.
Using onSetup
onSetup
is a complex property. It takes a function that is passed the component’s API and should return a callback that is passed the component’s API and returns nothing. This occurs because onSetup
runs whenever the component is rendered, and the returned callback is executed when the component is destroyed. This is essentially an onTeardown
handler, and can be used to unbind events and callbacks.
To clarify, in code onSetup
may look like this:
onSetup: (api) => {
// Do something here on component render, like set component properties or bind an event listener
return (api) => {
// Do something here on teardown, like unbind an event listener
};
};
To bind a callback function to an editor event use editor.on(eventName, callback)
. To unbind an event listener use editor.off(eventName, callback)
. Any event listeners should be unbound in the teardown callback. The only editor event which does not need to be unbound is init
e.g. editor.on('init', callback)
.
|