Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read properties of undefined trigger when trying to click upon window load

I would like to trigger a timer to run upon my page loading for the first time.

This is what I have tried:

let countdown;
...
const buttons = document.querySelectorAll("[data-time]");
...
function timer(seconds) {
  // clear any existing timers
  clearInterval(countdown);
  const now = Date.now();
  const then = now + seconds * 1000;
  displayTimeLeft(seconds);
  displayEndTime(then);
...
function startTimer() {
  const seconds = parseInt(this.dataset.time);
  timer(seconds);
}
...
window.addEventListener('load', buttons[0].addEventListener('click', startTimer).trigger('click'))

I get the error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Uncaught TypeError: Cannot read properties of undefined (reading 'trigger')

>Solution :

The easiest way would be doing like so :

window.addEventListener('load', startTimer)

I am not sure why you want to trigger the click event on the button, but if you have to, you should do something like that :

window.addEventListener('load', () => {
   buttons[0].addEventListener('click', startTimer)
   const event = new Event('click')
   buttons[0].dispatchEvent(event)
})

The error you have is due to the fact that addEventListener doesn’t return anything having a method called trigger (it doesn’t return anything at all).

But again, it should be enough to pass startTimer as a callback to the load event listener, no need to nest an additional event listener and trigger the click event on it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading