JavaScript JavaScript and the DOM Getting a Handle on the DOM A Simple Example

Maxim Melnic
Maxim Melnic
4,176 Points

Hi, why addEventListener don't work without function?

Hi, why addEventListener don't work without function?

for example:

const myHeading = document.getElementById("myHeading"); myHeading.addEventListener('click', 'myHeading.style.color = "red"');

I see an errore in console "Argument 2 of EventTarget.addEventListener is not an object"

In what sense?

Otec Perez Glass
Otec Perez Glass
7,678 Points

Hi Max Mel Hope you are doing good, the only issue is that you forgot to call the anonymous function or the call back function.

   const myHeading = document.getElementById("myHeading");
   myHeading.addEventListener('click', function () {
   myHeading.style.color = "red"; 
//One thing is that when you are calling the style object and its property in this case color it should not be inside quotes 

});

1 Answer

You need to put an anonymous function in so that the addEventListener method does not fire off immediately when the page loads. When you click then the new function executes what needs to be done.

myHeading.addEventListener('click', 'myHeading.style.color = "red"');

Will immediately change to red.

Antonio Ascue Avalos
Antonio Ascue Avalos
3,022 Points

Doesn't work. The color remains black despite clicking on the title. Why?, I am using Chrome.