Why is 'textarea' returning null even on input?

Viewed 41

I'm writing a code on speed typing test, and I would like to start the timer when the user inputs the texteare for the first time. However, the textarea doesn't seem to be logging in my input changes and console is returning an error message saying addEventListener cannot return a property of null.

HTML CODE

    <section class="typing">
        <div class="timer" id="timer"><h1>60</h1></div>
        <div class="container">
            <div class="word-display" id="word-display">
                <p>Typing Test</p>
            </div>
            <textarea id="word-input" class="word-input" rows="7" placeholder="Start Typing" name="word-input"></textarea>
        </div>
    </section>

JAVA CODE


function startTimer() {
    
    startTime = new Date();
    setInterval(() => {
        document.querySelector('#timer').innerText = getTimerTime()}, 1000);
};

function getTimerTime () {
    return (60 - Math.floor((new Date() - startTime) / 1000));
};

document.querySelector('DOMContentLoaded', onload = generateWordSpan, onkeyup = checkWord, function() {
    if (document.querySelector('#word-input')) {
        document.querySelector('#word-input').addEventListener('onchange', startTimer, {once: true})    
    };
});
1 Answers

The trick to have an event listener to start an interval is the {once: true} option.
That make the event fire only once.

Then... within the interval, you do what you like.

const maxTime = 60 // seconds

const header = document.querySelector('#timer h1')
const input = document.querySelector("#word-input")

function startTimer() {
  const startTime = new Date();
  let timeIsUP = 0
  const intervalId = setInterval(() => {
    timeIsUP = maxTime - Math.floor((new Date() - startTime) / 1000)
    header.innerText = (timeIsUP);

    if (timeIsUP < 0) {
      clearInterval(intervalId)

      if (input.value.length > 100) {
        header.innerText = "Good work. We'll call you."
      }
      if (input.value.length > 300) {
        header.innerText = "We hire you for monday."
      }
      if (input.value.length > 800) {
        header.innerText = "SuperStar! How many vacation weeks you want?"
      }
      if (input.value.length > 6000) {
        header.innerText = "Cheater!"
      }
    }
  }, 1000);

};

input.addEventListener("keyup", startTimer, {
  once: true
})
#word-input {
  width: 100%;
}
<section class="typing">
  <div class="timer" id="timer">
    <h1>60</h1>
  </div>
  <div class="container">
    <div class="word-display" id="word-display">
      <p>Typing Test</p>
    </div>
    <textarea id="word-input" class="word-input" rows="7" placeholder="Start Typing" name="word-input"></textarea>
  </div>
</section>

Related