Failed to execute 'addEventListener' on 'EventTarget'

Viewed 22227

I struggle with a javascript error, that I cannot get rid of: Uncaught TypeError: Failed to execute 'addEventListener' on 'EventTarget': The callback provided as parameter 2 is not an object.

This is the script, that is used in a cookie consent module after the tag:

window.addEventListener("load", setTimeout(   function(){
  window.cookieconsent.initialise({ 
  "palette": { "popup": {"background": "#DCDCDC"}, 
              "button": {"background": "#9bba44"}
              }, 
  "position": "bottom-right", 
  "content": { "message": "We use cookies.", 
               "accept": "Accept all", 
               "deny": "Decline all",
               "link": "Find out more." } 
  })
}, 3000));
</script>

If needed I can look into cookieconsent.initialise, but the error may be something else, more trivial to anyone with experience. What is the second parameter here?

1 Answers

The 2nd parameter of window.addEventListener should be a function.

What you have boils down to:

window.addEventListener("load", setTimeout(function(){ /* stuff */}, 3000));

That setTimeout is called the moment you call addEventListener, and the return value of setTimeout (The timeout id) is passed to addEventListener.

You need to wrap the setTimeout in a function:

window.addEventListener("load", () => setTimeout(function(){
    /* stuff */
}, 3000));

Now, you're passing a function to addEventListener that can be called on the load event. That function will set a new timeout.

Related