The empty spaces are ignored by the "InnerText" property

Issue

I want that when i press on any keyboard key the string which is stored in the "array" variable (as an array) be written in the "p" element but the problem is that when I put an empty space in the "string" variable(by tab key or space key) it doesn’t write those empty spaces, so the sentence would be like this: "Helloworld".

window.onload = () => {
    let log = document.getElementById("log");
}
let string = "  Hello world \n  How are you ?";
let array = string.split("");
let i = 0;
log.addEventListener("click", () => {
    document.addEventListener("keypress", type);
})
function type() {
    log.innerText += array[i];
    i++;
    if (array[i] === undefined) {
        document.removeEventListener("keypress", type);
    }
}
#log {
    height: 50vh;
    width: 450px;
    padding: 15px;
    position: absolute;
    left: 10px;
    color: rgb(0, 255, 0);
    font-size: 18px;
    background-color: rgba(0, 0, 0, 0.7);
    border-radius: 25px;
}
#log::after {
    content: "";
    position: absolute;
    width: 7px;
    height: 20px;
    background-color: rgb(0, 255, 0);
    animation-name: green;
    animation-duration: 1s;
    animation-iteration-count: infinite;
}
@keyframes green {
    0% {background-color: rgb(0, 255, 0);}
    25% {background-color: transparent;}
    50% {background-color: rgb(0, 255, 0);}
    75% {background-color: transparent;}
    100% {background-color: rgb(0, 255, 0);}
}
<p id="log"></p>

Solution

Rather than reading from element.innerText, store the "text so far" in another string variable, and set the innerText to the value of that variable.

window.onload = () => {
    let log = document.getElementById("log");
}
let string = "  Hello world \n\tHow are you ?";
let array = string.split("");
let i = 0;
let words = "";
log.addEventListener("click", () => {
    document.addEventListener("keypress", type);
})
function type() {
    words += array[i];
    log.innerText = words;
    i++;
    if (array[i] === undefined) {
        document.removeEventListener("keypress", type);
    }
}
#log {
    height: 50vh;
    width: 450px;
    padding: 15px;
    position: absolute;
    left: 10px;
    color: rgb(0, 255, 0);
    font-size: 18px;
    background-color: rgba(0, 0, 0, 0.7);
    border-radius: 25px;
}
#log::after {
    content: "";
    position: absolute;
    width: 7px;
    height: 20px;
    background-color: rgb(0, 255, 0);
    animation-name: green;
    animation-duration: 1s;
    animation-iteration-count: infinite;
}
@keyframes green {
    0% {background-color: rgb(0, 255, 0);}
    25% {background-color: transparent;}
    50% {background-color: rgb(0, 255, 0);}
    75% {background-color: transparent;}
    100% {background-color: rgb(0, 255, 0);}
}
<pre id="log"></pre>

Answered By – James

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.