Home > Back-end >  Add Click event on an image using Typescript
Add Click event on an image using Typescript

Time:12-27

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:

  1. In typescript, you cannot have attribute declarations (like private spinner: HTMLImageElement;) and method calls (like this.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 a class, which you wanted, though I'm not entirely sure. If you actually wanted this within a normal function, then you may not use private at all).
  2. 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.
  3. Passing this.test to addEventListener directly - 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 method private 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.

  • Related