0

I have this for loop in a chrome extension that creates image elements based on an api

for (var i = 0; i <= 2; i++) {
    //a
    var a = document.createElement("a");
    //a.setAttribute("href", "embed.html");
    a.setAttribute("id", "image"+i);

    //img
    var img = document.createElement("img");
    img.setAttribute("width", "192");
    img.setAttribute("height", "108");
    img.src =  resp.videos[i].thumbnail;
    var src = document.getElementById("disp");

    img.addEventListener("click", handleClick(i));

    a.appendChild(img);
    src.appendChild(a);
}

And this function that gets called by the event listener

function handleClick(id) {
   chrome.storage.sync.set({'id': id}, function() {
      console.log(id);
   });
  chrome.storage.sync.set({'pathName': pathName}, function() {
      console.log(pathName);
   });
}

But when one of them is pressed the function all of them get executed and because of this it ends up always saving the last one to local storage.

How can I get the event listener to only run for the one that is pressed?

HEXICLE
  • 39
  • 3
  • 1
    handleClick(i) is not a function reference, but a function invocation. There are several ways to rework the code, you can find examples on stack overflow e.g. [Javascript event handler with parameters](//stackoverflow.com/q/10000083) but personally I would simply use one `handleCick` listener without parameters and instead add an expando property on the image itself `img.originalId = i` and then use it in the listener. – wOxxOm Jul 26 '17 at 04:32
  • For more complex arguments, this is easily solved using `.bind()`. However, given that you're just passing a portion of the `id`, you should just get the information from `event.target.id.replace('image','')`, using a separate `event.target.dataset.imageNumber` (alternately `setAttribute`/`getAttribute`), or, as has been already suggested, an expando property. – Makyen Jul 26 '17 at 20:37

0 Answers0