I have a simple text editor and i'd like to toggle h1 tags around the current selection as i do with bold tags. With bold tags i do:
function onBoldClick() {
document.execCommand( 'bold', false );
}
This automatically toggles b tags around the current selection.
With h1 tags:
function onHeading1Click() {
document.execCommand('formatBlock', false, '<h1>');
}
This only wraps h1 around the selection but there's no way to remove it.
Is there another way to go about this?
Nb: it should work on i.e.
var h1Class = 'your h1 btn class',
removeH1Class = '.remove-h1';
$(document).on('click', h1Class, function() {
$(this).removeClass(h1Class).addClass(removeH1Class);
onHeading1Click();
});
$(document).on('click', removeH1Class, function() {
$(this).removeClass(removeH1Class).addClass(h1Class);
onRemoveH1Click();
});
function onHeading1Click() {
document.execCommand('formatBlock', false, '<h1>');
}
function onRemoveH1Click() {
document.execCommand('formatBlock', false, 'p');
}
HTML
<p><button type="button" id="h1-button">H1</button></p>
<div id="edit-area" contenteditable="true">
<h1>This is heading</h1>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed posuere interdum sem. Quisque ligula eros ullamcorper quis, lacinia quis facilisis sed sapien. Mauris varius diam vitae arcu. Sed arcu lectus auctor vitae, consectetuer et venenatis eget velit. Sed augue orci, lacinia eu tincidunt et eleifend nec lacus. Donec ultricies nisl ut felis, suspendisse potenti.</div>
</div>
Javascript + jQuery
$('#h1-button').click(function() {
var html = $('#edit-area').html();
document.execCommand('formatBlock', false, 'h1');
if(html == $('#edit-area').html()) {
document.execCommand('formatBlock', false, 'div');
}
});
JSFIDDLE DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With