Home > Software design >  Why is 'textarea' returning null even on input?
Why is 'textarea' returning null even on input?

Time:09-12

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 >
        <div  id="timer"><h1>60</h1></div>
        <div >
            <div  id="word-display">
                <p>Typing Test</p>
            </div>
            <textarea id="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', onl oad = generateWordSpan, onkeyup = checkWord, function() {
    if (document.querySelector('#word-input')) {
        document.querySelector('#word-input').addEventListener('onchange', startTimer, {once: true})    
    };
});

CodePudding user response:

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 >
  <div  id="timer">
    <h1>60</h1>
  </div>
  <div >
    <div  id="word-display">
      <p>Typing Test</p>
    </div>
    <textarea id="word-input"  rows="7" placeholder="Start Typing" name="word-input"></textarea>
  </div>
</section>

CodePudding user response:

This is JavaScript

  • #Timer is the id for the div not the h1 tag
  • Consider using event listener keypress or keydown
  • Not to be condescending but it is not that hard. Maybe write down what you are trying to do. I think you're overthinking it.
  • Related