1

I'm trying to create an on click event that will load a specific image based on the button being clicked. Currently my html is:

  <nav>
    <a class="link" href="#">1</a>
    <a class="link" href="#">2</a>
    <a class="link" href="#">3</a>
    <a class="link" href="#">4</a>
    <a class="link" href="#">5</a>
    <a class="link" href="#">6</a>
    <a class="link" href="#">7</a>
    <a class="link" href="#">8</a>
    <a class="link" href="#">9</a>
    <a class="link" href="#">10</a>
    <a class="link" href="#">11</a>
  </nav>
  <div id="image"></div>

Based on the link, I want each of these to load the associated image:

var item = document.querySelectorAll(".link");
var itemID = [];

for (var x = 0; x < item.length; x++) {
    itemID[x] = x + 1;
  }
for (var i = 0; i < (item.length); i++) {
  img = itemID[i];
  item[i].addEventListener("click", function(){
    document.querySelector("#image").innerHTML = '<img src="' + img + '.png">';
  });
}

The code is loading the image properly, but it only ever loads "11.png" for every link. Link 1 should load 1.png, Link 2 should load 2.png, etc.

I'm not sure what I'm doing wrong but I feel I'm misunderstanding how to use addEventListener correctly? Any help would very welcome!

1 Answer 1

2

The problem is here: img = itemID[I]; img is not declared and is global, so on every iteration it change value and so the old tag img change src accordingly.

Try to declare a new img on every iteration:

let img = itemID[i];
Sign up to request clarification or add additional context in comments.

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.