Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Toggling H1 and h2 with execCommand

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.

like image 900
Skyalchemist Avatar asked Dec 26 '22 12:12


2 Answers

var h1Class = 'your h1 btn class',
    removeH1Class = '.remove-h1';

$(document).on('click', h1Class, function() {

$(document).on('click', removeH1Class, function() {

function onHeading1Click() {
    document.execCommand('formatBlock', false, '<h1>'); 
function onRemoveH1Click() {
    document.execCommand('formatBlock', false, 'p'); 
like image 123
Tommy Adey Avatar answered Dec 28 '22 03:12

Tommy Adey


 <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>

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');


like image 41
Rane Avatar answered Dec 28 '22 01:12