I am making a web based code editor and am using a textarea for text editing. I want to add tab support to the textarea so that pressing tab doesn't de-focus the element. I have the textarea defined like this:
<textarea id="codeEdit_txt" rows="50" cols="80" onkeydown="return codeEdit_keyDown(event);">
and the function codeEdit_keyDown defined as:
function codeEdit_keyDown(e) {
if (e.keyCode == 9) {
return false;
}
}
This prevents the tab key press from de-focusing the textarea, though it doesn't leave the tab character behind. While I was trying to get this to work initially, I noticed that if I defined the function as below, it would put a tab character at the cursor position.
function codeEdit_keyDown(e) {
if (e.keyCode == 9) {
alert("");
return false;
}
}
My two questions are:
- Why does adding the alert cause a tab to be added?
- Is there a way to add the tab at the cursor without having to find the cursor position, split the text in the texarea and manually add a tab character (and without having to have an alert every time the user pressed tab)?
Thanks
EDIT: This only seems to work in Chrome, not in IE, Safari or Firefox