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 trialxxx xxx
5,272 Pointstried to implement for loop to hook up html buttons to their methods but failed
var playlist = new Playlist()
var buttonNames = ["play","next","stop"]
for(var i=0; i<buttonNames.length; i++) { var buttonName = buttonNames[i]; var button = document.getElementById(buttonName); button.onclick = function() { alert(buttonName); } }
However all 3 buttons only do a alert("stop")
What am i missing here?
3 Answers
Jacob Bergdahl
29,119 PointsYour for loop will run immediately when your site loads. It will go through all your variables. Your last variable value is "stop". buttonName will be overwritten with this value, and thus the you're redefining the function every time. A better approach would be to try and extract the function, rather than having an anonymous such.
xxx xxx
5,272 PointsI am actually a newbie in Javascript. It will be nice if you can show me in code what you mean by extract the function. Appreciate it.
Jacob Bergdahl
29,119 PointsI think it'd be easier if you follow along with the course, learn more about functions, and then come back and try to solve this later :) You'll learn much more if you first fully understand how methods work.
Tushar Singh
Courses Plus Student 8,692 PointsActually jacob is right, direct answers won't help you in any way. Go through your videos again and solve the challenge. If you are still stuck, google and MDN are your best friends.
xxx xxx
5,272 PointsFor anyone who is interested
http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example
Not giving out answers here but pointing to the right direction
Leonardo Hernandez
13,798 PointsLeonardo Hernandez
13,798 PointsI think I know why this is happening: All of them say "stop" because the onclick function was last set as: alert(buttonName)
buttonName is the last item in your array so when you go to click your "play" button. JavaScript doesn't see: function() { alert("Play"); }
It reads like this: function() { alert(buttonName); } }
So what does button name equal? It equals the last thing you set it to: buttonName = "Stop";
So try: (Copy what is inside the loop below, I added the an expression to your onclick function. )