Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow Tabbing in a contentEditable div with execCommand

I am making an application where I need for a contentEditable div to be allowed to have tabs in it. I have already figured out that it is really not possible to have to work correctly. So is there a way that on keyDown it adds the HTML code for a tab, which is

	

What I have so far is this

document.getElementById('codeline').contentEditable='true';
document.getElementById('codeline').onkeydown=function(e){
    if(e.keyCode==9){
        e.preventDefault();
        //document.getElementById('codeline').contentWindow.document.execCommand("InsertHTML",false,"	"); 
        //Thought this would work but it doesn't
    }
}

If anybody knows if there is a way to do this, or if that is the way and I am simply doing it wrong, please tell me! Thanks!

like image 746
comu Avatar asked Oct 08 '11 18:10

comu


2 Answers

The HTML spec specifies that a TAB char should be treated as a single white space except for when it's contained inside a <pre> element.

The code that you posted above does work and it does insert a TAB char but it's just displayed by the browser as a white space. If you can put your entire editable content in a <pre> tag then your tabs will show up.

If you only want to use the tabs to indent content, you can also look into

execCommand('indent', false, null)

like image 124
dcro Avatar answered Sep 23 '22 05:09

dcro


For future readers, perhaps a simpler solution is to just use the 'pre' white-space style. original post here.

white-space: pre;
like image 35
Warpling Avatar answered Sep 25 '22 05:09

Warpling