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 trialSean Gabriel Villoria
8,515 PointsWhy doesn't my arrow function work in my addEventListener?
I created this arrow function in app.js but ran into an error:
"Uncaught TypeError: Cannot set property 'display' of undefined"
button.addEventListener('click', () => {
game.startGame()
this.style.display = 'none';
document.getElementById('play-area').style.opacity = '1';
});
I double checked my code and the block was the same as the solution just not as an arrow function. Tried it as below and it worked:
button.addEventListener('click', function(){
game.startGame()
this.style.display = 'none';
document.getElementById('play-area').style.opacity = '1';
});
Did I declare my arrow function wrong? Or is it not possible to use arrow functions in instances like this?
Thanks!
1 Answer
Brandon White
Full Stack JavaScript Techdegree Graduate 34,662 PointsHi Sean,
Arrow functions do not have their own this. It doesn't bind this like the function keyword does, so yes, that it why this is undefined in the first code example.
In this case you'll want to use the function keyword, or you write your callback to accept the event parameter, like so:
button.addEventListener('click', (evt) => {
game.startGame()
evt.target.style.display = 'none';
document.getElementById('play-area').style.opacity = '1';
});
In this case, evt is the click event, and the target is the button that receives the event. As such you can change the style for the button that way.
Hope that helps. Great question! :)
Sean Gabriel Villoria
8,515 PointsSean Gabriel Villoria
8,515 PointsGot it. Thanks Brandon!