JSFiddle - React, Tailwind, and code Playground
by mqchen
HTML
<button data-write-role="button">bold</button>
<div class="editor" contenteditable="true">
<p>123 <a href="#">hello <strong>world</strong></a></p>
asdf
</div>
CSS
.editor {
padding: 20px;
margin: 20px 0;
border: 1px solid #cdcdcd;
}
[data-write-role="selection"] {
background-color: yellow;
border: 1px solid #666;
}
JavaScript
var Write = function(element) {
this.editor = $(element);
this.selection = $();
};
Write.prototype.getSelection = function() {
// Remove old selection
console.debug("Selection", this.selection.html());
// this.selection.unwrap();
return this.selection = $(this._wrapSelection($('<span data-write-role="selection"></span>')[0]));
};
Write.prototype._wrapSelection = function(wrapElement) {
var selObj = window.getSelection();
var selRange = selObj.getRangeAt(0);
var documentFragment = selRange.extractContents();
wrapElement.appendChild(documentFragment);
selRange.insertNode(wrapElement);
return wrapElement;
};
Write.prototype.wrapInline = function(wrapperElementPrototype, elementsToWrap) {
console.debug(elementsToWrap);
};
var write = new Write($(".editor"));
$("[data-write-role]").each(function(index, item) {
$(item).on("click", function(e) {
e.preventDefault();
// console.debug(write.getSelection());
write.wrapInline($("<strong>"), write.getSelection().contents());
});
});