Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting loses caret position on <pre> element on pressing TAB key

I have pre with contentEditable="true" on my webpage and I am trying to make it append "\t" when I press <TAB>. I found some other plugins for that but they were working only on <textarea>.

So, the problem is that when I append text to the <pre> through jQuery, it loses the caret position. I was sure it was losing focus but it's not. So $("pre").focus(), will do nothing.

I tried to blur it first but this is not practical cause the caret will return on different position depending on the browser. some help please... :P,

My code is here: http://jsfiddle.net/parisk/kPRpj/

like image 697
Paris Avatar asked Feb 23 '11 10:02

Paris


1 Answers

Try using document.execCommand instead. Here’s a demo. In short:

$("pre").keydown(function(e){
    if (e.keyCode==9) {
        e.preventDefault();
        document.execCommand('InsertHTML', false, '\t');
    }
});
like image 120
s4y Avatar answered Oct 29 '22 11:10

s4y