0

I'm attaching elements created by Javascript inside a for loop. What I'm trying to achieve is different variables passed to a function for each element.

Here's my code:

var thumbnail_box = document.createElement("div");
thumbnail_box.onmouseenter = function(){show_new_attachement_toolbar(total_upload)};
thumbnail_box.onmouseleave = function(){hide_new_attachement_toolbar(total_upload)};

the variable total_upload is automatically incremented in the end of each loop, however when all the elements are added, the function only triggers for the final value of total_upload instead of separate value for each element

Zaiat
  • 68
  • 1
  • 4

1 Answers1

0

A simple fix would be to wrap that code in an IIFE:

(function(x) {
  var thumbnail_box = document.createElement("div");
  thumbnail_box.onmouseenter = function () { show_new_attachement_toolbar(x) };
  thumbnail_box.onmouseleave = function () { hide_new_attachement_toolbar(x) };
})(total_upload);

You might need to read this

Giovanni Londero
  • 1,309
  • 1
  • 10
  • 20