ckeditor demo

by Zeljko Tadic

HTML

<script src="//cdn.ckeditor.com/4.5.1/standard/ckeditor.js"></script>
<textarea name="editor1" id="editor1" rows="10" cols="80"></textarea>

JavaScript

CKEDITOR.plugins.add('marker_plugin', {
  init: function(editor) {

    editor.addCommand('highlight', {
      exec: function(editor) {
        markCurrentSelection("#FEF7A9");
      }
    });

    editor.ui.addButton('Highlight', {
      label: 'Highlight',
      command: 'highlight',
    });

    var config = editor.config;

    function markCurrentSelection(color) {
      editor.focus();
      editor.fire('saveSnapshot');

      var styleDefinition = {
        element: 'span',
        styles: {
          'background-color': '#(color)'
        },
        attributes: {
          'class': 'marker'
        }
      };

      editor.removeStyle(new CKEDITOR.style(styleDefinition, {
        color: 'inherit'
      }));

      styleDefinition.childRule =
        function(element) {
          return isUnstylable(element);
        };

      editor.focus();
      editor.applyStyle(new CKEDITOR.style(styleDefinition, {
        color: color
      }));
      editor.fire('saveSnapshot');
    }

    function isUnstylable(ele) {
      return (ele.getAttribute('contentEditable') == 'false') || ele.getAttribute('data-nostyle');
    }

    // Function suggested by ztadic91
    function updateMarker() {
          debugger;

      var document = new CKEDITOR.dom.document(document);
      var elements = document.find('.current'); // Fire error "Cannot read property 'querySelectorAll' of undefined"
      for (var i = 0; i < elements.length; i++) {
        var activeElement = elements[i];
        activeElement.removeClass('current');
      }
      this.addClass('current');
    }

    function refreshState() {
      var editable = editor.editable();
      if (!editable) {
        return;
      }
      var element = editable.getDocument().getSelection().getStartElement();
      if (element !== null) {
        if (element.hasClass('marker')) {
          updateMarker();
        }
      }
    }
    editor.on('selectionCheck', refreshState); // Event that detects all the selection changes.
 ...