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 JavaScript and the DOM (Retiring) Making Changes to the DOM Styling Elements

how can I declare the function later in the script rather than putting it in the event listener?

at 3:51 in the video

Hi Jaime, you would have to pass the function as a argument to the eventlistener. You can name your function any name you want. I chose the name myFunction for this example. Hope this answers your question.

toggelList.addEventListener('click', myFunction);


function myFunction(){
//code goes here//
}

1 Answer

would it still work if the function that you're passing is an arrow function also? i can get my code to work if its an arrow function but i can if its a standard function.

The problem is that when you declare an arrow function it has to be declared before the event listener is created. When using a function declarationit does not matter where the function is created in the document.

Arrow function:

let ul = document.querySelector('ul');

const myFunction = (e)=>{
   e.target.style.color = 'red';
  }

ul.addEventListener('click', myFunction);

Function declaration:

let ul = document.querySelector('ul');



ul.addEventListener('click', myFunction)

function myFunction(e){
  e.target.style.color = 'red'

}