0

I have a single input to upload a image.

html

<main>
    <input id="hs-p" type="file" accept="image/*" capture="camera">
</main>

<script type="text/javascript">
    let hsp = new HPS();
</script>

I want to listen for when this input changes ( when someones adds an image to it).

js

let imageInput = null;

class HSP {       
    constructor() {

        this.imageInput = document.getElementById('hs-p');

        if (this.imageInput) {
            this.imageInput.addEventListener("change", this.uploadImage());
        }
   }

    uploadImage() {
        console.log("upload image", this.imageInput);
    }
}

module.exports = HSP;

When someone adds an image it should call the uploadImage callaback. However this function is only firing once when the page loads and never fires when i add a image to the input or change the input image.

I am using node & webpack to output the above custom library/sdk which i then import into my html.

leonheess
  • 16,068
  • 14
  • 77
  • 112
Kay
  • 17,906
  • 63
  • 162
  • 270

2 Answers2

6

Change your event to this:

this.imageInput.addEventListener("change", () => this.uploadImage());

Or to this:

this.imageInput.addEventListener("change", this.uploadImage.bind(this));

What you are doing is calling uploadImage and passing the result of that to the listener. You want to pass the reference to the listener.

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
0

change this.imageInput.addEventListener("change", this.uploadImage()); to this.imageInput.addEventListener("change", this.uploadImage); ( removed the () after this.uploadImage ).