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
Pieter Bracke
4,078 PointsHiding and showing images javascript
Hi, I am making an assignment for my school but can't quite figure this one out.
I want to show and hide different images by clicking dynamically added buttons through javascript.
Beneath is my function to add all the buttons this works fine Then below that I thought I would try to loop through each created button and adding an event handler to each of them, and then defining a function to each of the eventhandlers that way. However that doesn't seem to work all that well... Function for this is below the addButtons().
Any idea how I should solve this?
javascript
function addButtons(){
var eKnoppen = document.getElementsByClassName('toggle');
var eKnoppenLength = eKnoppen.length;
var eScreenShots = document.getElementsByClassName('screenshot');
for(var i = 0; i < eKnoppenLength; i++){
var createKnop = document.createElement('button');
createKnop.setAttribute('class', 'knop');
createKnop.setAttribute('id', 'knop' + i);
createKnop.innerHTML = "verberg screenshot";
eKnoppen[i].insertBefore(createKnop,eScreenShots[i]);
}
}
function hideSingle(){
var eKnoppen = document.getElementsByClassName('knop');
var eKnoppenLength = eKnoppen.length;
console.log(eKnoppen);
var eScreenshots = document.getElementsByClassName('screenshot');
for(var i = 0; i < eKnoppenLength; i++){
eKnoppen[i].addEventListener('click', function(){
eKnoppen[i].innerHTML = "Toon screenshot";
eScreenshots[i].style.display = "none";
})
}
}
1 Answer
Steven Parker
243,658 PointsBy sharing the loop variable, the event handlers will no longer reference the correct (or even a valid) element when they are invoked. Be sure that each handler has a unique value:
for(var i = 0; i < eKnoppenLength; i++){ // instead of this...
for(let i = 0; i < eKnoppenLength; i++){ // ...do THIS