I have a contenteditable
div
with div
s inside them like this:
<div id="wrapper" contenteditable=true onkeydown="preventTab(event);">
<div id="line1" class="line"></div>
<div id="line2" class="line"></div>
<div id="line3" class="line"></div>
<div id="line4" class="line"></div>
</div>
With CSS, using ::before
for line numbers , this looks like this:
Now, I want, whenever someone presses tab, it automatically inserts four spaces instead of a tab. I got this function, but it doesn't do anything after it has fired the events.
function preventTab(event) {
event = event || window.event;
if (event.keyCode === 9) {
// for loop, so the user can set the amount of spaces they want.
for (let i = 0; i < tabSize; i++) {
let e = new KeyboardEvent("keydown", {
bubbles: true,
code: "Space",
key: " ",
keyCode: 32
});
event.target.dispatchEvent(e);
}
event.preventDefault();
}
}
As I said, nothing really happens (maybe because isTrusted: false
?), also no errors are thrown.
By the way, I have noticed this question with the same title, but that heavily depends on the jQuery library and I'm looking for a pure JavaScript approach.