Reputation: 479
I'm having a text editor inside a contenteditable div.
I need to change the [TAB] behavior to insert spaces or a \t instead of focusing on next element which is the default browser behavior.
I have an event handler like so:
function keyDown(e) {
// press tab.
if (e.keyCode == 9) {
e.preventDefault();
return;
}
}
which results in not losing focus on the div, all i need now is to insert a [TAB] or spaces at the cursor position.
how can this be done?
Upvotes: 3
Views: 2557
Reputation: 3498
This will do the trick: http://jsfiddle.net/eFLGZ/
$('textarea').keydown(keyDown);
function keyDown(e) {
// press tab.
if (e.keyCode == 9) {
e.preventDefault();
// Insert a space.
var txt = $('textarea').val();
$('textarea').val(txt + ' ');
return;
}
}
See here for how to enter the text where the cursor is currently placed.
Upvotes: 3