1

I'm trying to create jQuery that will indent a div when the tab key is pressed. I found this code, which works fine:

$('[contenteditable]').on('keydown', function(e) {
    if(e.keyCode == 9){
        e.preventDefault();
        document.execCommand('insertHTML', false, '&#009');
    }
});

However, when looking at the API documentation (https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand), it states:

Obsolete
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

Are there any alternatives to using .execCommand()?

Carson D
  • 81
  • 13
  • This is surprisingly complicated. You first need to check whether the user has highlighted something (`window.getSelection()`) or just has his cursor somewhere in your div, and if the latter, then where. You may check out questions like [this one](https://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container) and [this one](https://stackoverflow.com/questions/16736680/get-caret-index-in-contenteditable-div-including-tags) on that topic. Then you can do the easy part, replacing/inserting the content with something like `insertAdjacentHTML`. – cjl750 Apr 24 '20 at 22:52

0 Answers0