0

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?

Peverell
  • 1
  • 1
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Mark Schultheiss Feb 03 '22 at 22:04
  • 1
    You mentioned that you tried `image.addEventListener` but shouldn't that be: `img.addEventListener`? – Simon K Feb 03 '22 at 22:04
  • [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) doesn't really help me because I'm not using jQuery. It being `image.addEventListener` instead of `img.addEventListener` is a typo. – Peverell Feb 04 '22 at 19:36

1 Answers1

0

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
Casper Kuethe
  • 1,070
  • 8
  • 13
  • This does allow me to get images that I can click on but they appear on the document body and not on specific spots on a canvas where I want them. – Peverell Feb 04 '22 at 19:38
  • I read more about DOM and there no way to append elements to a canvas. Is there any way to have a clickable image in the canvas or do something similar to append elements to the canvas. – Peverell Feb 04 '22 at 20:15
  • Ah it’s on a Canvas. Then You have to add the event listener on the canvas element and track your image position so you can check whether the mouse x and y are inside the image boundaries when you click on the canvas. – Casper Kuethe Feb 04 '22 at 23:13