Reputation: 154573
If I'm typing text in a input field and press ENTER
the default behavior of all the browsers I know is to submit the form, however if I press ENTER
inside a textarea a new line is added.
Is there any way to mimic this behavior (indent, not submit the form) whenever I press TAB
inside a textarea? Bespin seems to do it, but in a canvas
element.
Upvotes: 2
Views: 4878
Reputation: 1
This code should work.
//'index.js' File
var textarea = document.getElementById('note');
textarea.addEventListener('keydown', function (e) {
if(e.keyCode==9) {
e.element().insert("\t");
e.stop();
}
});
If you get a 'cannot read property of null' error do this:
//'index.js' File v2
function tab() {
var textarea = document.getElementById('note');
if(event.keyCode===9) {
textarea.innerHTML += "\t";
}
}
The HTML should follow suit and look like this:
<!DOCTYPE html>
<!-- index.html -->
<!-- Don't Mind the other parts like the style and button tags -->
<!-- If you don't get the error mentioned just remove the 'onkeydown="tab()"'. -->
<html onkeydown="tab()">
<head>
<title>Calender</title>
<script src="./index.js"></script>
<style>
* {
background-color: darkgoldenrod;
color: white;
}
textarea {
background-color: white;
color: black;
}
.newNote {
background-color: olivedrab;
color: white;
border: 1px solid #000000;
box-shadow: none;
border-radius: 7.5px;
}
</style>
</head>
<body>
<button class="newNote" id="newNote" onclick="Note()">New Note</button>
<br/>
<br/>
<textarea wrap="soft" rows="30" cols="100" id="note"
placeholder="Type a Note Here!" title="Note Box"></textarea>
</body>
</html>
Upvotes: 0
Reputation: 449525
I haven't done it myself, but it seems to be possible to override the event handler and catch the key. See e.g. here.
Oh and for the JQuery crowd there even is a plugin.
Upvotes: 10
Reputation: 26971
Of course there's a way. Do you use any js library? If not, the idea is just to add a keydown event handler on the textarea element, check in the handler if the keyCode of the event equals 9, and if so append a "\t" to the content of the textarea. Prototype snippet:
textarea.observe('keydown', function (e) {
if(e.keyCode==9) {
e.element().insert("\t");
e.stop();
}
}
Upvotes: 2