Create your own command button in CKEditor


In this article, I will show you how to create a customized command button in CKEditor, go along with an example project to help you understand and imagine what can we do with CKEditor.
In this article, I will show you how to create a customized command button in CKEditor, go along with an example project to help you understand and imagine what can we do with CKEditor.

Written by Minh Tuan Do


Posted at 04 Jul 2019, 10:24 PM



Introduction

CKEditor is a very popular text editor for most developers, because it's open source and easy to use. It provides many ways to configure and customize to get a best fit editor to your application. What we often do is choosing a best version of CKEditor, then choose what feature to use by modifying it's config.js file or use Online Toolbar Configurator. But don't you know you can do more with CKEditor by adding your own button and handle your specific business. This article will show you how.

Getting started

Before we start, the following prerequisite knowledge is required for you:

  • Basic knowledge about web development
  • You are expected to know what the CKEditor is, how to download and embed it to your website
  • Basic command with CKEditor like: how to make the editor visible, how to modify config file

If you are not familiar with the editor, try reading the documentation first.

Example project

This project is a demo version in which you can learn how to customize CKE to serve your business demand. It's not a professional real-life project so there is no data validation, we assume that every input would be in a correct format.

Imagine you are working for a daily news company and is responsible for posting daily weather forecast. Your partner company sends to you the data about weather information in your country. Their temperature data uses Fahrenheit, but in your country Celsius is more popular. Everytime you receive the data, you need to calculate and convert °F to °C using the formula: T(°C) = (T(°F) - 32) × 5/9 . The idea is creating a customized button on your editor, and easily you can highlight some text like "93°F" and click on the button to convert to °C. It's faster and more convenience than using copy and paste to another tool.

Getting things ready

You are expected to get the editor ready to work.

  1. <textarea id="editor"></textarea>
  2.  
  3. <script src="~/Scripts/ckeditor/ckeditor.js"></script>
  4.  
  5. <script>
  6.     var editor = CKEDITOR.replace('editor');
  7. </script>
 

Adding a button

To add a new custom button to CKEditor, use this code:

  1. editor.ui.addButton('ConvertFtoC', //button name
  2.         {
  3.             label: 'Convert Fahrenheit to Celsius', //button tooltips (will show up when mouse hovers over the button)
  4.             command: 'cmd_convert_F_to_C', // command which is fired to handle event when the button is clicked
  5.             toolbar: 'others', //name of the toolbar group in which the new button is added
  6.             icon: '/Content/images/convert.svg' //path to the button's icon
  7.         }
  8.     );

Command can be declared before or after we add a button.

Toolbar is the name of the toolbar group in which the button is inserted. You can check some toolbar name at this link

Adding a command

To add a new command to process when the button is clicked, use this code:

  1. editor.addCommand("cmd_convert_F_to_C", {
  2.         exec: function (edt) {
  3.             //Do something here           
  4.         }
  5.     });

The first parameter of addCommand method is the command name. It must be the same as the command name we assign to the new button. 

Now, when you click the button name ConvertFtoC, the command cmd_convert_F_to_C would be executed.

If your code works, you should see the new button appears, otherwise check your code and fix error.


Get highlighted text

To get the highlighted text, use this code:

  1. var mySelection = editor.getSelection();
  2.             var selectedText;
  3.  
  4.             //Handle for the old Internet Explorer browser
  5.             if (mySelection.getType() == CKEDITOR.SELECTION_TEXT) {
  6.                 if (CKEDITOR.env.ie) {
  7.                     mySelection.unlock(true);
  8.                     selectedText = mySelection.getNative().createRange().text;
  9.                 } else {
  10.                     selectedText = mySelection.getNative();
  11.                 }
  12.             }
  13.  
  14.             var plainSelectedText = selectedText.toString();
 

 Please be noticed that

selectedText = mySelection.getNative();
returns a HTML DOM element. It means we can treat it like an element and modify it normally such as adding an attribute or change its css style properties. To get the plain text of the selection, use the ToString method.

 Replace highlighted text

To replace the highlighted text by another text, simply insert the new text to our editor. If there is some text highlighted, it will be replaced by the new one, just like we highlight text and start typing. 

You can also create a new HTML element to insert, not only plain text. HTML element allows us to work more creative, means we can add css style, give it some attribute such as an id to retrived, and anything you need to modify your element. In this case, I create a span tag and insert it to replace the old highlighted text.

  1. var insertedElement = editor.document.createElement('span');
  2.  
  3. insertedElement.setAttribute('style', 'color: red');
  4.  
  5. insertedElement.appendText("Hello world!");
  6.  
  7. //replace reselected text by the new span element
  8. editor.insertElement(insertedElement);

 Finally, your command should be like this:

  1. editor.addCommand("cmd_convert_F_to_C", {
  2.         exec: function (edt) {
  3.             var mySelection = editor.getSelection();
  4.             var selectedText;
  5.  
  6.             //Handle for the old Internet Explorer browser
  7.             if (mySelection.getType() == CKEDITOR.SELECTION_TEXT) {
  8.                 if (CKEDITOR.env.ie) {
  9.                     mySelection.unlock(true);
  10.                     selectedText = mySelection.getNative().createRange().text;
  11.                 } else {
  12.                     selectedText = mySelection.getNative();
  13.                 }
  14.             }
  15.             var plainSelectedText = selectedText.toString();
  16.  
  17.             //Process converting
  18.             var regex = /[+-]?\d+(\.\d+)?/g; //regex for float number
  19.  
  20.             if (plainSelectedText.match(regex) != null) { //check if there is a float number in selected text
  21.  
  22.                 var fahrenheit = plainSelectedText.match(regex).map(function (v) { return parseFloat(v); });
  23.  
  24.                 if (!isNaN(fahrenheit)) {
  25.  
  26.                     var insertedElement = editor.document.createElement('span');
  27.  
  28.                     var result = (fahrenheit - 32) * (5 / 9);
  29.  
  30.                     //37 °C is too hot! warn user by red text
  31.                     if (result > 37) {
  32.                         insertedElement.setAttribute('style', 'color: red');
  33.                     }
  34.  
  35.                     insertedElement.appendText(result + " °C");
  36.  
  37.                     //replace reselected text by the new span element
  38.                     editor.insertElement(insertedElement);
  39.                 }
  40.             }
  41.  
  42.         }
  43.     });

And because there is all written in javascript, means you can do more with this command, like contacting a DOM element or sending an AJAX request. 

See your result

Copy some data and try to select the ...°F data, then click the button to see the result. The new °C value will be calculated and then replace the old °F value. 

And here is the result we have achieved:

Conclusion

 CKEditor is easy to use, provides many approachs to customize and supports a lot of features. By reading it's document and research, you will find out there are more than just a command button, but also many things we can do with it in a higher level. You can even replace it's base procession by your own. My example project is just a little one to help you understand this, but by doing a deep research, we can optimize it's features and help us a lot in editing text.

 

 

 



Comments


Search