Sometimes, we want to add a custom button to the toolbar that calls a JavaScript function with CKEditor.
In this article, we’ll look at how to add a custom button to the toolbar that calls a JavaScript function with CKEditor.
Add a Custom Button to the Toolbar that Calls a JavaScript Function with CKEditor
To add a custom button to the toolbar that calls a JavaScript function with CKEditor, we can add a command with the addCommand
method.
Then we can add a method that calls the command with the addButton
method.
For instance, we can add the editor with:
<script src="https://cdn.ckeditor.com/4.16.1/standard/ckeditor.js"></script>
<textarea id="container">How are you!</textarea>
Then we write:
const editor = CKEDITOR.replace('container');
editor.addCommand("mySimpleCommand", {
exec(edt) {
console.log(edt.getData());
}
});
editor.ui.addButton('SuperButton', {
label: "Click me",
command: 'mySimpleCommand',
toolbar: 'insert',
icon: 'https://avatars1.githubusercontent.com/u/5500999?v=2&s=16'
});
to create the editor with:
const editor = CKEDITOR.replace('container');
Then we add a command with:
editor.addCommand("mySimpleCommand", {
exec(edt) {
console.log(edt.getData());
}
});
The first argument is the name of the command.
The 2nd argument is an object with the exec
method that has the code for the command.
We just call getData
to get the input value of the text editor.
Next, we call ui.addButton
with the button name the first argument.
Then 2nd argument has the settings for the button, which includes the command
property set to the command that we want to run.
The icon
is the URL for the icon.
Conclusion
To add a custom button to the toolbar that calls a JavaScript function with CKEditor, we can add a command with the addCommand
method.
Then we can add a method that calls the command with the addButton
method.