ckeditor demo
by Richard
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 removeHighlights() {
var document1 = CKEDITOR.instances.editor1.document;
var elements = document1.find('.current');
elements.$.forEach(function(el) {
el.classList.remove('current');
});
}
// Function suggested by ztadic91
function updateMarker(element) {
removeHighlights();
element.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(element);
} else {
removeHighlights();
}
}
}
editor.on('selectionCheck', refreshState); // Event that detects all the selection changes.
...