HTML Editor
by meziantou
HTML
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<h1>HTML Editor</h1>
<div class="editor-commands">
<ul>
<li><a data-command="undo">Undo</a></li>
<li><a data-command="redo">Redo</a></li>
<li><a data-command="insertHorizontalRule">hr</a></li>
<li><a data-command="bold">Bold</a></li>
<li><a data-command="italic">Italic</a></li>
<li><a data-command="underline">Underline</a></li>
<li><a data-command="strikeThrough">strikeThrough</a></li>
<li><a data-command="justifyLeft">justifyLeft</a></li>
<li><a data-command="justifyCenter">justifyCenter</a></li>
<li><a data-command="justifyRight">justifyRight</a></li>
<li><a data-command="justifyFull">justifyFull</a></li>
<li><a data-command="indent">indent</a></li>
<li><a data-command="outdent">outdent</a></li>
<li><a data-command="insertUnorderedList">insertUnorderedList</a></li>
<li><a data-command="insertOrderedList">insertOrderedList</a></li>
<li><a data-command="html" data-command-argument="h1">h1</a></li>
<li><a data-command="html" data-command-argument="h2">h2</a></li>
<li><a data-command="html" data-command-argument="h3">h3</a></li>
<li><a data-command="html" data-command-argument="p">p</a></li>
<li><a data-command="subscript">subscript</a></li>
<li><a data-command="superscript">superscript</a></li>
</ul>
</div>
<div id="Editor" class="editor" contenteditable="true"></div>
<button id="PreviewButton">View HTML</button>
<div id="Preview"></div>
CSS
.editor {
min-height: 300px;
width: 100%;
border: 1px solid black;
}
JavaScript
var commandButtons = document.querySelectorAll(".editor-commands a");
for (var i = 0; i < commandButtons.length; i++) {
commandButtons[i].addEventListener("mousedown", function (e) {
e.preventDefault();
//var editor = document.getElementById("editor");
var commandName = e.target.getAttribute("data-command");
if (commandName === "html") {
var commandArgument = e.target.getAttribute("data-command-argument");
document.execCommand('formatBlock', false, commandArgument);
} else {
document.execCommand(commandName, false);
}
});
}
document.getElementById("PreviewButton").addEventListener("click", function(e) {
e.preventDefault();
document.getElementById("Preview").innerText = document.getElementById("Editor").innerHTML;
});