Simple Rich Text Editor with Contenteditable and JavaScript
Basic WYSIWYG example
by Roko
HTML
<div class="editButtons">
<span title="STYLES">
<button data-edit="bold"><b>B</b></button>
<button data-edit="italic"><i>I</i></button>
<button data-edit="underline"><u>U</u></button>
<button data-edit="strikeThrough"><s>S</s></button>
</span>
<span title="TEXT FORMAT">
<button data-edit="formatBlock:p">P</button>
<button data-edit="formatBlock:H1">H1</button>
<button data-edit="formatBlock:H2">H2</button>
<button data-edit="formatBlock:H3">H3</button>
</span>
<span title="FONT SIZE">
<button data-edit="fontSize:1">↥s</button>
<button data-edit="fontSize:3">↥M</button>
<button data-edit="fontSize:5">↥L</button>
</span>
<span title="LISTS">
<button data-edit="insertUnorderedList">UL</button>
<button data-edit="insertOrderedList">OL</button>
</span>
<span title="ALIGNMENT">
<button data-edit="justifyLeft">⇤</button>
<button data-edit="justifyCenter">↔</button>
<button data-edit="justifyRight">⇥</button>
</span>
<span title="CLEAR FORMATTING">
<button data-edit="removeFormat">×</button>
</span>
</div>
<div contenteditable>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
<sub>Tip: you can drag images or links from another tab</sub>
CSS
.editButtons span{
display:inline-block;
white-space:nowrap;
}
[data-edit] {
float:left;
border:0;
font: 12px/1 monospace;
background:#ddd;
padding:4px 8px;
}
[contenteditable] {
padding:4px 16px;
background:#eee;
}
JavaScript
document.querySelectorAll("[data-edit]").forEach(btn =>
btn.addEventListener("click", edit)
);
function edit(ev) {
ev.preventDefault();
const cmd_val = this.getAttribute("data-edit").split(":");
document.execCommand(cmd_val[0], false, cmd_val[1]);
}