HTML5 Rich Text Editor

by stackmanoz

HTML

<p id="cp">
    <a href="#bold" id="bold" class="bold btn">B</a>
    <a href="#italic" id="italic" class="italic btn">I</a>
    <a href="#underline" id="underline" class="underline btn">U</a>
    <a href="#h2" id="h2" class="btn">h1</a>
    <a href="#h3" id="h3" class="btn">h2</a>
</p>
<div id="box" contenteditable="true">
    Please type here
</div>

<p><a href="#edit" id="edit">Edit Markup</a> - This markup will be submitted to the database.</p>

<textarea id="markup"></textarea>

CSS

a { color: #FF5E99; }
#box { padding: 10px; border: 1px solid #999; width: 80%; height: 200px; margin: 10px; font-family: Calibri, Sans-Serif; }
#markup { display: none; padding: 10px; border: 1px solid red; width: 80%; height: 50px; margin: 10px; font-family: Calibri, Sans-Serif; }

.bold {font-weight:bold;}
.italic {font-style:italic;}
.underline {text-decoration:underline;}
.btn { width: 20px; height: 20px; padding: 5px; background-color: #CCC; border: 1px solid #999; display: inline-block; text-align: center; line-height: 20px; }

JavaScript

:)$("#markup").text($("#box").html());

$("#box").keyup(function() {
    $("#markup").text($("#box").html());
});

$("#cp a").click(function() {
    $("#markup").text($("#box").html());
});

$("#bold").click(function() {
    var elem = document.createElement('span');
        elem.innerHTML = ' bold';
        elem.classList.add('bold');
    
    document.getElementById('box').appendChild(elem);
    
    return false;
});

$("#italic").click(function() {
    var elem = document.createElement('span');
        elem.innerHTML = ' italic';
        elem.classList.add('italic');
    
    document.getElementById('box').appendChild(elem);
    
    return false;
});

$("#underline").click(function() {
    var elem = document.createElement('span');
        elem.innerHTML = ' underline';
        elem.classList.add('underline');
    
    document.getElementById('box').appendChild(elem);
    
    return false;
});

$("#h2").click(function() {
    var elem = document.createElement('h2');
        elem.innerHTML = '~ Title';
    
    document.getElementById('box').appendChild(elem);
    
    return false;
});

$("#h3").click(function() {
    var elem = document.createElement('h3');
        elem.innerHTML = '+ Title';
    
    document.getElementById('box').appendChild(elem);
    
    return false;
});

$("#edit").click(function() {
    $("#markup").fadeIn(1000);
    
    return false;
});