<nav><button id="bold" value="bold">B</button>
<button id="italic" value="italic"><i>I<i></button>
<button id="underline" value="underline">U</button>
<button id="cut" value="cut">Cut</button>
<button id="copy" value="copy">Copy</button>
<button id="paste" value="paste">Paste</button>
<button id="sub" value="subscript">Sub</button>
<button id="super" value="superscript">Super</button>
</nav>
<section id="editbox" contenteditable="true"><b>
This text can be edited simply by clicking and selecting it, just like in any text editor. Also try to make the text bold and italic by selecting it and using the buttons. If you make a <i>change</i>, try refreshing the browser.
</b></section>
JavaScript
var App = {
init: function () {
//Each time we type something, save it
document.getElementById('editbox').addEventListener('keyup', App.saveData);
//Event listeners for the bold and italic buttons
document.getElementById('bold').addEventListener('click', App.toggleBold);
document.getElementById('italic').addEventListener('click', App.toggleItalic);
document.getElementById('underline').addEventListener('click', App.toggleUnderline);
document.getElementById('cut').addEventListener('click', App.toggleCut);
document.getElementById('sub').addEventListener('click', App.toggleSub);
document.getElementById('super').addEventListener('click', App.toggleSuper);
App.restore();
},
saveData: function () {
//Save the data
localStorage.document = document.getElementById('editbox').innerHTML;
},
toggleBold: function () {
//Set the selection to bold and save the data
document.execCommand('bold',false,null);
App.saveData(null);
},
toggleItalic: function () {
//Set the selection to italic and save the data
document.execCommand("italic");
App.saveData(null);
},
toggleUnderline: function () {
document.execCommand("underline");
},
toggleCut: function () {
},
toggleSub: function () {
document.execCommand("subscript");
},
toggleSuper: function () {
document.execCommand("superscript");
},
restore: function () {
//If we have already a saved document, restore it on startup
if(localStorage.document){
document.getElementById('editbox').innerHTML = localStorage.document;
}
}
};
document.addEventListener('DOMContentLoaded', App.init(), false);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.