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

mck89 picture mck89 · Feb 10, 2010 · Viewed 17.6k times · Source

I'm building a simple text editor by setting contentEditable=true on a div (anyway i think that textarea behaves in the same way) and i have some problems with the tab key.

What i want is that when the user presses the tab key, the focus remain on the div and a tab character is added to the text.

I've solved the first part of the problem by calling preventDefault() on the event object on keydown and now the div doesn't lose the focus, but i don't know why i can't insert the character.

The entity code for the tab char is 	 but if i try to add this string to the innerHTML Firefox replace it with a simple space (not   just a white space). I also tried with \t but the result is the same.

So my question is, how can I insert a tab character in the text?

Answer

Michael Sabin picture Michael Sabin · Aug 20, 2015

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);
    }
}