Skip to content
Advertisement

( ) => in addEventListener wont be executed

I’m pretty new to JavaScript and I struggle extending existing code of my coworker.

What I try to achieve:

  1. Get all images with id = yt
  2. add an EventListener to all
  3. Call method to replace the image depending on the event error target

I already implemented to logic, an this code works:

export class ImageYt{
    
    initialize() {
        var yt = document.querySelectorAll('#yt');

        for (var i = 0; i < yt.length;  i++) {
            yt[i].addEventListener('error', this.setThumbnail(yt[i]));
        }
    }

    setThumbnail(yt){
        yt.setAttribute('src', 'placeholder');
    }

}

But I would like to extend the EventListener with an event (to use it later) like this:

yt[i].addEventListener('error', (event) => this.setThumbnail(yt[i]));

But then my code is not working and the method setThumbnail wont be called anymore. I asume it has something to do with ( ) =>. I had a look on different documentations and this type of function call is limited, maybe the problem is that I call the addEventListener multiple times? I know this will be inherited from the declaring scope but tbh I don’t understand the mechanic enough to have a proper soultion.

Advertisement

Answer

  1. IDs need to be unique so document.querySelectorAll('#yt'); may work but is very much not recommended
  2. Use function if you want to use this – arrow functions do not have this
  3. addEventListener('error', this.setThumbnail(yt[i])) would not add an event listener but instead add the result of the setThumbnail which is not a function

This works – I am using a class

const imageList = document.querySelectorAll('.imgError');
imageList.forEach(img => img.addEventListener('error', function() { // here you can use this
    this.setAttribute('src', 'https://www.freeiconspng.com/uploads/error-icon-24.png')
}));
// trigger the error
imageList.forEach(img => img.src = "does not exist")
<img class="imgError" />
<img class="imgError" />
<img class="imgError" />
<img class="imgError" />
<img class="imgError" />
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement