There is an example below. How to make it so that when Tab is pressed, an indent is inserted in the text (paragraph) instead of moving to the next page element?

<div class='test' contentEditable='true'>Some text</div> 

    1 answer 1

    Recently reworked for myself the similar from the answer to EN.SO

     let divs = document.getElementsByClassName("test"); [].forEach.call(divs, function(item) { item.addEventListener("keydown", function(e) { if (e.keyCode === 9) { e.preventDefault(); let div = this; let selection = div.ownerDocument.defaultView.getSelection(); let range = selection.getRangeAt(0); let tab = document.createTextNode("\u00a0\u00a0\u00a0\u00a0"); range.insertNode(tab); range.setStartAfter(tab); range.setEndAfter(tab); selection.removeAllRanges(); selection.addRange(range); } }) }) 
     <div class='test' id="editor" contentEditable='true'> Some text</div> 

    • And move the cursor? - user207618
    • @Other, moves the same? - Moonvvell
    • And why 4 spaces, but not one tabulation? ) - Sasha Omelchenko
    • After your update - yes, it moves. - user207618
    • @SashaOmelchenko seems to be the case that if the div is not in pre then the tabulation will be interpreted as a space. I had a problem with that. - Moonvvell