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 trialSahan Balasuriya
10,115 PointsHow does it know which button I clicked?
So I wondering how to the console know which button we clicked. The for loop loops till buttons.length so If I click button how will it know to stop at 5 so that i = 5. I can see the addEventListener but I'm assuming this is only for the alert message.
1 Answer
Steven Parker
231,275 PointsThe loop puts a separate listener function on each button, and each function contains the button number inside it. The loop finishes before any buttons can be clicked.
But later, when you click on a button, only the function that was attached to that specific button runs.
Sahan Balasuriya
10,115 PointsSahan Balasuriya
10,115 Pointsstill a it confused, could you show me the listener function
Steven Parker
231,275 PointsSteven Parker
231,275 PointsThe addEventListener takes another function as an argument. This other function is the one that will run when the button is clicked. The important point is that each button has it's own version of this function to run when it is clicked.
Brandon Lopez
2,045 PointsBrandon Lopez
2,045 PointsSteven Parker- So are you saying each button is storing different data? (storing the unique function inside the button) And if so how does the button store data?
Steven Parker
231,275 PointsSteven Parker
231,275 PointsThe addEventListener function stores the function and any variables that are part of the function scope in system memory (not "inside the button"), and associates it with the button. See the documentation page for addEventListener for more details.
Steve Gallant
14,943 PointsSteve Gallant
14,943 PointsThis was so helpful. The video explains what happens but not really why. Thanks!