I’d like to write my own hackertyper site that prints itself when pressing some keys.
But when I try the code below, it prints everything at the same line. I used template literals (``)
and couldn’t make it. Then tried <br />
in the string but also not worked. How do I make it right?
Edit: I was using <p>
tag in the HTML file, when I changed it to <pre>
tag as Praveen said, it solved my problem. Thank you.
JavaScript
x
19
19
1
"use strict";
2
3
let str = `"use strict"
4
5
let str = "";
6
7
let emptyStr = "";
8
let i = 0;
9
document.addEventListener("keydown", function () {
10
emptyStr += str.charAt(i++) + str.charAt(i++) + str.charAt(i++);
11
document.querySelector("#string").textContent = emptyStr;
12
});`;
13
14
let emptyStr = "";
15
let i = 0;
16
document.addEventListener("keydown", function () {
17
emptyStr += str.charAt(i++) + str.charAt(i++) + str.charAt(i++);
18
document.querySelector("#string").textContent = emptyStr;
19
});
JavaScript
1
1
1
<p id="string"></p>
Advertisement
Answer
I guess if you’re trying to print it out, you need to print it out on a <pre>
tag or an element with style white-space: pre
or similar.
Here’s an example with <pre>
tag:
JavaScript
1
11
11
1
let str = `This is HackerTyper
2
3
See I have spaces and lines!`;
4
5
let emptyStr = "";
6
7
let i = 0;
8
document.addEventListener("keydown", function () {
9
emptyStr += str.charAt(i++) + str.charAt(i++) + str.charAt(i++);
10
document.querySelector("#string").textContent = emptyStr;
11
});
JavaScript
1
1
1
<pre id="string"></pre>
Here’s the same with white-space: pre
for <div>
:
JavaScript
1
11
11
1
let str = `This is HackerTyper
2
3
See I have spaces and lines!`;
4
5
let emptyStr = "";
6
7
let i = 0;
8
document.addEventListener("keydown", function () {
9
emptyStr += str.charAt(i++) + str.charAt(i++) + str.charAt(i++);
10
document.querySelector("#string").textContent = emptyStr;
11
});
JavaScript
1
3
1
div {
2
white-space: pre;
3
}
JavaScript
1
1
1
<div id="string"></div>
And, finally, just wanted to tell, this is a really good implementation of HackerTyper.