I'm learning TypeScript and I'm trying to add a click event on an image. There are no errors in the console and the program runs ok in the browser, but I cannot trigger the click event.
Here's my code:
private spinner: HTMLImageElement = new Image();
//Also tried to initialise like this:
//private spinner: HTMLImageElement;
//this.spinner = document.createElement("img");
this.spinner.src = "graphics/image_name.png"
this.spinner.addEventListener("click", this.test);
//Also tested this:
//this.spinner.onclick = this.test;
Any help would really be appreciated, because I can't find anything online that explains what I'm doing wrong.
CodePudding user response:
Several issues:
- In typescript, you cannot have attribute declarations (like
private spinner: HTMLImageElement;) and method calls (likethis.spinner.addEventListener() on the same level (in the class scope) - The latter needs to go to some method. (I'm just going to assume that it was aclass, which you wanted, though I'm not entirely sure. If you actually wanted this within a normal function, then you may not useprivateat all). - The spinner you're creating needs to be attached to the DOM somehow (e.g using
document.body.append(this.spinner)- but I guess you just didn't copy that part to your StackOverflow question or otherwise you wouldn't see the image in the first place. - Passing
this.testtoaddEventListenerdirectly - like you did - would work, but usually isn't a good idea, as you would then not be able to access attributes from within your methodprivate test() { //... }.) - To solve that, use an arrow function instead - e.g.:() => this.test()instead.
Here's a working sample: https://stackblitz.com/edit/typescript-jriy5b?devtoolsheight=33&file=index.ts
I just added the code for the event listener in the class' constructor, but of course you could use it in any method you like.
