1

I am trying to make a loop that will display some images and add an event listener to each image which, when clicked will assign the appropriate value to humanGoal. I have:

var humanGoal;

function displayPicker(round){
    for(var i = 0; i <= round; i++){
        document.write('<img src=img/die' + i + '.png id="' + 'picker' + i + '">');
        document.getElementById('picker'+i).addEventListener("click", function () {
            humanGoal = i;
            document.write('you picked ' + humanGoal );
        });
    }
}

why does humanGoal always === round+1, instead of the variable i from the for loop?

1
  • try i.toString() Commented Mar 29, 2017 at 19:05

2 Answers 2

1

The humanGoal variable is being overwrited with every for loop iteration and holds the round + 1 value at the end. Different words speaking - it will always display a wrong index.

Solution: apply same class to the each img element, bind a click event listener and display the actual index by passing i variable inside the Array#forEach function.

function displayPicker(round){
    for (var i = 0; i <= round; i++){
      document.write('<img src=img/die' + i + '.png id="' + 'picker' + i + '" class="img">');
    }
    var elems = document.getElementsByClassName('img');
        Array.from(elems).forEach((v,i) => v.addEventListener('click', function() {
          console.log(`You picked ${i}`);
        }));
}

displayPicker(5);

Sign up to request clarification or add additional context in comments.

Comments

0

See answer to your question is simple, when you were trying to assign human goal with value of i, the loop is already been iterated over "rounds" value that why you always getting i === round inside click function.

See the below code snippet,

<html>
	<script>
	var humanGoal;

		function displayPicker(round){
			for(var i = 0; i <= round; i++){
				document.write('<img src=img/die' + i + '.png id="' + 'picker' + i + '">');
				document.getElementById('picker'+i).addEventListener("click", function () {
					console.log("me getting called second");
					humanGoal = i;
					document.body.append('you picked ' + humanGoal );
				});
				console.log("me getting called first");
			}
		}
	
	</script>
	<body onload="displayPicker(4)">
	</body>
</html>

for getting the correct result you can follow the approach provided by @Kind user

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.