Search code examples
javascriptexeccommand

JavaScript Outdent text in contenteditable


I am trying to indent and outdent in a contenteditable div. The indenting works perfectly but the outdent execCommand isn't working. I have a last key buffer that works for other keyboard shortcuts but not this one. Thank you for any help.

        if (keyCode == 9) { /* indent */
            event.preventDefault();
            document.execCommand("indent");
        }
        if(keyCode == 9 && lastkey == 16){
            event.preventDefault();
            document.execCommand("outdent");
        }

Solution

  • You should be using an if / else if so that you're only running one of the two commands, and also have the lastKey check as the first in the series

    I'm not sure how your lastKey variable was working, so I've added event.shiftKey for demo

    $(".myClass").on("keydown", function(event) {
      if (event.keyCode == 9 && event.shiftKey /* lastKey */ ) {
        event.preventDefault();
        document.execCommand("outdent");
      } else if (event.keyCode == 9) { /* indent */
        event.preventDefault();
        document.execCommand("indent");
      }
    });
    .myClass {
      display: block;
      height: 300px;
      width: 500px;
      border: 1px solid #bfbfbf;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="myClass" contenteditable="true"></div>