Skip to content
Advertisement

Can you attach a handler function with arguments to an onclick event for a number of elements in a loop?

I am trying to set an onclick event for thumbnails that are dynamically populated from a database. I need to set the function to handle an argument, which is the id of the bigger picture the thumbnail represents. The code I have now sets all the thumbnails to point to #18. If you see in the for-loop, it is supposed to die at 17:

for (var i = 0; i < 18; i++) {
    document.getElementById('tat' + i).onclick = function() { display(i); }; 
}

(My thumbnail <img />s all have id="tat0", id="tat1", id="tat2", id="tat3" etc.) (display() loads the larger pic that the thumbnail represents into a separate element)

Each thumbnail gets this onclick function, so I know the for loop is accessing each one by its ID properly (stepping through for each i) so why are all the display(i) being assigned to 18? Can you assign an onclick function to handle parameters?

Advertisement

Answer

You need a closure function to generate your handlers.

function genHandler( param ) {
  return function() {
     // use all params in here
     display( param );
  }
}

and then assign your events similarly

for (var i = 0; i < 18; i++) {
  document.getElementById('tat' + i).onclick = genHandler( i );
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement