0

I have a problem with this code.

var uls = document.getElementsByClassName("gal");

for (var i = 0; i < uls.length; i++) {

    // impossible to pass uls[i] as callback argument (undefined in callback)
    uls[i].addEventListener("click", function() { openSlideShowModal(uls[i].tagName);} );
}

I have the error : Uncaught TypeError: Cannot read property 'tagName' of undefined

I can't explained why uls[i] is undefined as it is global. I know that there's no use of it because it could be accessible by this in the callback. But i found this incomprehensible error by chance.

Moreover if i modify slightly i no longer have an error

var uls = document.getElementsByClassName("gal");

for (var i = 0; i < uls.length; i++) {

    tagName = uls[i].tagName;
    // impossible to pass uls[i] as callback argument (undefined in callback)
    uls[i].addEventListener("click", function() { openSlideShowModal(tagName);} );
} 
Emile
  • 1

1 Answers1

0

A bind this should help you out getting the function back into the same context where ever it is being called.

function() { 
    openSlideShowModal(uls[i].tagName);
}.bind(this)
marpme
  • 2,363
  • 1
  • 15
  • 24