I'm trying to create a bunch of images inside js and add Event Listeners to each of them so that they trigger function when clicked.
I use this function to create images.
function image(fileName) {
const img = new Image(100, 100);
img.src = `images/${fileName}`;
return img;
}
When I try to add an event listener with
image.addEventListener(...)
It compiles but doesn't work when drawing the images later.
I have also tried adding an id to the image and using getElementById() to add the listener, it doesn't compile with the event listener reading null.
Any suggestions?
The eventListeners only work when the element is added to the DOM, which isn't in your case.
If you add your image to the DOM then you can add a working evenListener.
function image(fileName) {
const img = new Image(100, 100);
img.src = `images/${fileName}`;
// Or any other node
document.body.appendChild(img);
return img;
}
// Now you can bind eventListeners to the returned img element