Reputation: 87
I am working on a little script here using contenteditable.
It's toggling / untoggling bold, underline, italic, but I can't make it untoggle font-size. It toggles it and then it stays that way.
Working demo: https://jsfiddle.net/zesaj9ck/2/
<button id="toggle_bolt" onclick="document.execCommand('italic');">toggle italic</button>
<button id="toggle_bolt" onclick="document.execCommand('underline');">toggle underline</button>
<button id="toggle_bolt" onclick="document.execCommand('fontSize', false, 7);">toggle size</button>
<div id="wmd-input" contenteditable="true"></div>
Upvotes: 1
Views: 388
Reputation: 8472
It's not "toggling" or changing at all after the first click because each click just sets the size to 7. Font size doesn't just have two states like bold, italic, and underline. The working example below takes a specified size value from an input instead.
I also recommend moving your click handlers to functions, as I've done with the changeSize
function. This creates a clearer separation of concerns and improves maintainability.
function changeSize(increase) {
var value = parseInt(document.getElementById('size').value, 10) + (increase ? 1 : -1);
document.execCommand('fontSize', false, value);
document.getElementById('size').value = value;
}
#wmd-input {
width : 500px;
min-height : 100px;
border : 2px solid;
}
<button id="toggle_bolt" onclick="document.execCommand('bold');">toggle bolt</button>
<button id="toggle_bolt" onclick="document.execCommand('italic');">toggle italic</button>
<button id="toggle_bolt" onclick="document.execCommand('underline');">toggle underline</button>
<button id="toggle_bolt" onclick="changeSize(true)">Size +</button>
<button id="toggle_bolt" onclick="changeSize(false)">Size -</button>
<input id="size" value="4" readonly />
<div id="wmd-input" contenteditable="true"></div>
Upvotes: 1