The element does not recognize the property 'width' since it is not defined in the type of 'GlobalEventHandlers'

I'm trying to determine the size of an image using JavaScript, but I encountered a TypeScript error:

const img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

How to get image size (height & width) using JavaScript?

Property 'width' does not exist on type 'GlobalEventHandlers'.

Any suggestions on how to resolve this issue?

Answer №1

The load handler does not have a specific type for 'this' when dealing with images. It is better to reference the image directly instead.

const img = new Image();
img.onload = function() {
  console.log(img.width + 'x' + img.height);
}

An alternative option is to use addEventListener.

img.addEventListener('load', function() {
  console.log(this.width + 'x' + this.height);
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Should we consider the implementation of private methods in Javascript to be beneficial?

During a conversation with another developer, the topic of hacking into JavaScript private functions arose and whether it is a viable option. Two alternatives were discussed: Using a constructor and prototype containing all functions, where non-API meth ...

What could be the reason for the component bindings being undefined within the controller?

I'm currently working on a basic angular component. I have set up a parameter as a binding and managed to display its value on the screen successfully. The parameter displays correctly, but when I try to access it within the controller, it shows undef ...

A comprehensive guide on personalizing Bootstrap 4 tooltips to suit your specific needs

I would like to customize the tooltip in Bootstrap 4 based on the screenshot provided below: https://i.stack.imgur.com/wg4Wu.jpg <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta chars ...

Developing a custom directive that utilizes a dynamic ng-options configuration

Alright, let me share with you my personalized directive: angular.module('bulwarkWebControls', []) .directive('customDropdown', [ function() { return { scope: { label: '@', // can be om ...

Why are my API routes being triggered during the build process of my NextJS project?

My project includes an API route that fetches data from my DataBase. This particular API route is triggered by a CRON job set up in Vercel. After each build of the project, new data gets added to the database. I suspect this might be due to NextJS pre-exe ...

Obtain the form value upon submission without the need to reload the page

I am facing an issue where I have a form and I want to trigger the display of a div (in the same page) and execute a JavaScript function upon clicking submit, all without causing a page refresh. <form action="#" method="post" name= "form1" id = "form ...

Extending the declaration of JavaScript native methods is not possible when using TypeScript

When attempting to enhance the JS native String class by adding a new method, I encounter error TS2339. interface String { transl(): string; } String.prototype.transl = function() { // TS2339: Property 'transl' does not exist on type 'St ...

What is the best approach to managing a 204 status in Typescript in conjunction with the Fetch API

Struggling to handle a 204 status response in my post request using fetch and typescript. I've attempted to return a promise with a null value, but it's not working as expected. postRequest = async <T>(url: string, body: any): Promise ...

The IDs and classes of HTML elements

I have two different implementations of a livechat script. On my sandbox site, the livechat is fixed to the bottom right of the page and scrolls with the window. However, on my live site (where this specific code comes from), it is attached to the footer. ...

`How to cleverly fake dependencies with symbols in Jest, Vue3, and Typescript?`

I am faced with the following scenario: // symbols.ts - Injection Key defined as a Symbol export const FAQ_SERVICE: InjectionKey<FAQService> = Symbol('FAQService'); // main.ts - globally provides a service using the injection key app.provi ...

Tips for invoking an Android function from an AngularJS directive?

I am facing an issue with my HTML that uses an AngularJS directive. This HTML file is being used in an Android WebView, and I want to be able to call an Android method from this directive (Learn how to call Android method from JS here). Below is the code ...

Are there equivalent npm variables like (`npm_config_`) available in yarn console scripts?

Utilizing variables in custom npm commands is possible (example taken from ): { "scripts": { "demo": "echo \"Hello $npm_config_first $npm_config_last\"" } } Can this functionality also be achieved ...

Using JavaScript/Angular to borrow a function and add additional parameters

In my scenario, I have a service function that requires a static parameter and a second custom parameter that changes based on the controller it is being used in. I am looking for a way for my controller/view to invoke this service function without havin ...

What is the proper way to transfer information to my ajax function from my controller?

I need to dynamically update an element on my webpage based on server-side code events. For example, when I trigger the "Start" function by clicking a button, I want the text inside a specific element to change to "Downloading", and then once the process i ...

Adding images to HTML using JavaScript below existing images

I'm currently working on a JavaScript game and I want to implement a feature where my character can move under blocks (isometric PNG images) instead of just sliding through them. Is there a way to dynamically adjust my character's position in the ...

Creating a flexible route path with additional query parameters

I am facing a challenge in creating a unique URL, similar to this format: http://localhost:3000/boarding-school/delhi-ncr However, when using router.push(), the dynamic URL is being duplicated like so: http://localhost:3000/boarding-school/boarding-school ...

Redirecting asynchronously in Node.js with no use of AJAX

I've been struggling with this issue for days and have already sought help, but nothing seems to be working. Whenever I attempt to redirect from a POST request in node, the browser doesn't respond. Here's how my app is structured: ./ confi ...

Exploring the nativeElement property of a customized Angular HTML element

In my Angular Jasmine Unit Test, I am testing a third-party slider component in my application using the following code snippet: Here is the HTML: <ui-switch id="EditSwitch" name="EditSwitch" (change)="togglePageState()"></ui-switch> And her ...

Transmit text from tinyMCE through AJAX in MVC architecture with PHP

I am currently facing an issue while trying to send POST data in the form of an array containing email elements such as subject and message. The problem arises when using tinyMCE for the subject part, which is not being sent through successfully. All other ...

Using Angular 2 to trigger an event when a native DOM element is loaded

I am working towards my main objective of having a textarea element automatically focused upon creation. I recently came up with an idea to use e.target.focus() on the onload event. It would look something like this: <textarea rows="8" col="60" (load)= ...