Search code examples
javascripthtmlcontenteditable

Javascript rich text editor, contenteditable area loses focus after button is clicked


I have simple javascript rich text editor consiting only of bold button that has following onclick:

  document.execCommand('bold', false)

And simple html...

<div contenteditable="true">

My problem is that when I click the bold button, text area loses it's focus, is there some solution for that?


Solution

  • Well the focus moves to the button so you need to cancel the click action so the focus is not lost in the content editable element.

    document.querySelector(".actions").addEventListener("mousedown", function (e) {
      var action = e.target.dataset.action;
      if (action) {
        document.execCommand(action, false)
        //prevent button from actually getting focused
        e.preventDefault();
      }
    })
    [contenteditable] {
      width: 300px;
      height: 300px;
      border: 1px solid black;
    }
    <div class="actions">
      <button data-action="bold">bold</button>
      <button data-action="italic">italic</button>
    </div>
    <div contenteditable="true"></div>