Reputation: 71
I am making a basic online editor using text area, i would like the editor to listen to keydown events. I have tried to make the code listen to the tab key pressed and then add space (4spaces) between the textcontent but it doesn't work. How can i go about this?
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<link rel="stylesheet" href="stylesheet.css">
<link rel="shortcut icon" href="">
<script>
document.addEventListener("keydown", logKey);
function logKey(key){
if (key.keyCode == "9"){
myTextArea.textContent += ' ';
}
}
</script>
</head>
<body>
<header>
<div class="navBar" id="heading-container"></div>
</header>
<textarea id="myTextArea">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent semper in nunc at mattis. Suspendisse metus augue, pellentesque finibus luctus dictum, tempor id nunc.
</body>
</html>
Upvotes: 3
Views: 1451
Reputation: 389
function logKey(key){
if (key.keyCode == "9"){
myTextArea.textContent += ' ';
key.preventDefault();
}
}
Closing Tag is good habbit of coder.. Don't forget to close < textarea >
Upvotes: 1
Reputation: 1073988
There are a few problems there:
keyCode
is a key code, not a character, which is a number.For the Tab key, use keyCode === 9
. This is one of the reliable key codes (not all key codes are across different keyboard layouts, etc.).
You're doing .value += ' '
, which will do this:
' '
to the end of it (regardless of where the insertion point was when the user pressed Tab)You're listening for Tab on document
, not just within the textarea
Your script
is in the head
, making it hard to fix #3. Normally, any non-async
, non-defer
, non-module script should be at the end of body
, just prior to the closing </body>
tag.
You're relying on the automatic global for myTextArea
. Although the creation of those automatic globals is standardized now, I strongly recommend not relying on them. Look up the elements you need using DOM APIs.
You probably want to prevent the default action of the Tab keypress.
#2 in particular will make a fairly poor user experience.
If you really want to do this, read up on execCommand
for #2. Example (also fixes the others mentioned):
document.getElementById("myTextArea").addEventListener("keydown", handleKey); // #3, #5
function handleKey(event){
if (event.keyCode === 9) { // #1
document.execCommand("insertText", true, " "); // #2
event.preventDefault(); // #6
}
}
<textarea id="myTextArea" cols=30 rows=10>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent semper in nunc at mattis. Suspendisse metus augue, pellentesque finibus luctus dictum, tempor id nunc.</textarea>
<!--
Stack Snippets handle #4 for you, by putting
the script after the HTML
-->
But as I said in a comment, I strongly recommend using something that's already been built and tested, like CodeMirror.
Upvotes: 4
Reputation: 191
Change your function to the one given below :
if (key.keyCode == "9"){
key.preventDefault();
myTextArea.value += ' ';
}
}
Upvotes: 1