Make the Tab key Insert a tab character in a contentEditable div and not blur

tabs and spaces are collapsed in html to one space unless in a <pre> tag or has white-space: pre in its style


Since the answer that was supposedly correct didn't work for me, I came up with this solution I think would work for more people.

$(document).on('keyup', '.editor', function(e){
  //detect 'tab' key
  if(e.keyCode == 9){
    //add tab
    document.execCommand('insertHTML', false, '&#009');
    //prevent focusing on next element
    e.preventDefault()   
  }
});

That code worked for me, but also make sure to include the white-space:pre-wrap attribute in your css. Hope this helped!


I know this is a bit old, but this ended up working the best for me...

function onKeyDown(e) {
    if (e.keyCode === 9) { // tab key
        e.preventDefault();  // this will prevent us from tabbing out of the editor

        // now insert four non-breaking spaces for the tab key
        var editor = document.getElementById("editor");
        var doc = editor.ownerDocument.defaultView;
        var sel = doc.getSelection();
        var range = sel.getRangeAt(0);

        var tabNode = document.createTextNode("\u00a0\u00a0\u00a0\u00a0");
        range.insertNode(tabNode);

        range.setStartAfter(tabNode);
        range.setEndAfter(tabNode); 
        sel.removeAllRanges();
        sel.addRange(range);
    }
}