Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript and the DOM (Retiring) Making Changes to the DOM Styling Elements

Jaime Aguilar
Jaime Aguilar
7,651 Points

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

Jaime Aguilar
Jaime Aguilar
7,651 Points

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'

}