Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Michael MacKenzie
Michael MacKenzie
7,336 Points

When I use an arrow function it works, but not when I use a function declaration.

All of my syntax is correct and I can get it working correctly but only when I use an arrow function. When I try to switch it to a normal function it starts applying the style as soon as I refresh the page before I even click. I have used normal functions to do similar things in my own little projects and they worked. Can anyone tell me why my normal function wont work here?

const p = document.getElementById('btn-main');

p.addEventListener('click', myFunc() );

function myFunc () {
 document.getElementById('headline').style.border = '1px solid red'; 
}

1 Answer

Steven Parker
Steven Parker
230,038 Points

When you put parentheses after a function name, it calls the function (immediately). But in this case you only want to identify the function so the listener mechanism can call it later when the click event occurs.

p.addEventListener('click', myFunc() );    // so instead of this ....
p.addEventListener('click', myFunc );      // just do THIS

You did not show an example of the arrow function, but I'd guess you were coding it in-line, so it was just being defined and not immediately called.