1

I invoked a callback onload and it worked but left a TypeError: Failed to execute 'addEventListener' on 'EventTarget': parameter 2 is not of type 'Object' in the console

document.addEventListener('load', setTimeout(callBack, 2000));

function callBack(){
    const data = JSON.parse(localStorage.data);
    const tbody = document.getElementById("info");
    for (let obj in data){
        let td = document.createElement('td');
        let text = document.createTextNode(`${data[obj]}`);
        td.appendChild(text);
        tbody.appendChild(td);
    }
};

There's a similar question here that prompted these changes:

document.addEventListener('load', function(){setTimeout(callBack, 2000)});

document.addEventListener('load', function(){setTimeout(callBack(), 2000)});

It doesn't display and I get no exceptions with the changes.

EDIT: On changing the event listener line, I get no data in my HTML- so callBack is not being handled or called.

23rdpro
  • 81
  • 1
  • 10

1 Answers1

0

With your sample code, you're calling a function and passing in that function's return value to the event listener.

You're supposed to pass in a function, and when the event occurs, the event listener executes that function for you.

window.addEventListener("DOMContentLoaded", function(e){
  setTimeout(callback, 2000);
});

function callback() {
  const data = JSON.parse(localStorage.data);
  const tbody = document.getElementById("info");
  for (let obj in data) {
    let td = document.createElement('td');
    let text = document.createTextNode(`${data[obj]}`);
    td.appendChild(text);
    tbody.appendChild(td);
  }
};
Aliza
  • 74
  • 4
  • I changed it to ```window.addEventListener("load", () => {setTimeout(callBack, 2000)});``` that's because [WINDOW object and DOCUMENT object ARE NOT THE SAME!!!!!](http://eligeske.com/jquery/what-is-the-difference-between-document-and-window-objects-2/) – 23rdpro Sep 26 '22 at 22:30