Search code examples
htmljquerycontenteditableexeccommand

My jquery execCommand isn't working as i want


I have this text editor which i created using jquery with execCommand and a div with contenteditable but some on it isn't working only the undo and redo is working. This is my code

<li data-role="bold" class="bold_str"><span><i class="fa fa-bold"></i></span></li>
<li data-role="strikeThrough" class="strike_str"><span><i class="fa fa-strikethrough"></i></span></li>
<li data-role="underline" class="underline_str"><span><i class="fa fa-underline"></i></span></li>
<li data-role="undo" class="undo_str"><span><i class="fa fa-undo"></i></span></li>
<li data-role="redo" class="redo_str"><span><i class="fa fa-redo"></i></span></li>


<div class="output_wp">
   <div class="output" id="output" contenteditable></div>
</div>


<script>
   $('li[data-role]').click(function () {
       document.execCommand($(this).data("role"), false);
    })
</script>

The bold, strikethrough and underline does not work when i highlight the text in the contenteditable div and click the li button

What do i do here cause console doesn't show any error and also whenever i click the li the highlight disappears and nothing will happen


Solution

  • (It's worth pointing out that execCommand is obsolete, and should not be used. See the answers to this question for more current alternatives.)

    execCommand acts on the "current editable region". Clicking on the li takes focus away from the editable region, so by the time your code runs there isn't a current editable region to act on.

    You can work around this by triggering the action on mousedown instead of on click, so it fires before the browser focus changes:

    $('li[data-role]').mousedown(function() {
      document.execCommand($(this).data("role"), false);
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <li data-role="bold" class="bold_str">Bold</li>
    <li data-role="strikeThrough" class="strike_str">Strikethrough</li>
    <li data-role="underline" class="underline_str">Underline</li>
    <li data-role="undo" class="undo_str">Undo</li>
    <li data-role="redo" class="redo_str">Redo</li>
    
    
    <div class="output_wp">
      <div class="output" id="output" contenteditable>lorem ipsum lorem ipsum</div>
    </div>