0

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.

2
  • What is this.test? Commented Dec 26, 2021 at 12:58
  • Sorry for not clarifying. It's just a function that changes a text element. I made it to check if the event works. Commented Dec 26, 2021 at 13:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for the working example. :D Yes, I did remove some of the code structure, which, in retrospect, I should have included.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.