Expand the prototype of HTMLElement

I'm attempting to enhance the prototype of the HTMLElement object in my main.ts file, with the intention of using it across my entire Angular 6 project.

However, I am encountering the error message:

Property 'fadeOut' does not exist on type 'HTMLElement'
.

HTMLElement.prototype.fadeOut = function(duration: number = 300): Promise<void> {
  const keyframes: AnimationKeyFrame[] = [{ opacity: 1 }, { opacity: 0 }];
  return new Promise(resolve => {
    const animation: Animation = this.animate(keyframes, duration);
    animation.onfinish = () => resolve();
  });
};

const circle = document.getElementById('circle');

HTMLElement.prototype.fadeOut = function(duration = 300) {
  const keyframes = [{ opacity: 1 }, { opacity: 0 }];
  return this.animate(keyframes, duration).finished
};

circle.fadeOut(2000);
#circle {
  height: 100px;
  width: 100px;
  margin: 50px;
  border-radius: 50%;
  background-color: #0f477f;
 }
 
<div id="circle"></>

What could be causing this issue?

Where should I place this code to ensure that the method is accessible globally?

Is there a way to refactor this code for improved clarity and efficiency?

Answer №1

To ensure proper merging with the original interface, you must include a definition where you define an additional function to be added to the HTMLElement interface.

interface HTMLElement {
    fadeOut(duration: number): Promise<void>
}

// This will make it work
HTMLElement.prototype.fadeOut = function (duration: number = 300): Promise<void> {
    const keyframes: AnimationKeyFrame[] = [{ opacity: 1 }, { opacity: 0 }];
    return new Promise(resolve => {
        const animation: Animation = this.animate(keyframes, duration);
        animation.onfinish = () => resolve();
    });
};

If your code is within a module, remember to declare the interface in the global namespace.

declare global {
    interface HTMLElement {
        fadeOut(duration: number): Promise<void>
    }

}
HTMLElement.prototype.fadeOut = function (duration: number = 300): Promise<void> {
    const keyframes: AnimationKeyFrame[] = [{ opacity: 1 }, { opacity: 0 }];
    return new Promise(resolve => {
        const animation: Animation = this.animate(keyframes, duration);
        animation.onfinish = () => resolve();
    });
};


export var x;

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

Preset for Typescript in Babel 6

Can anyone help me find a Babel preset for Typescript that is compatible with Babel 6, rather than Babel 7? I've been searching for this module with no luck. Is it possible that the TS preset is not supported for Babel 6? ...

How can I deactivate a particular button in a React application?

Is there a way to selectively disable a button from a set of buttons that are generated from server data? I need to disable a specific button, even if there are many others, and also make it so that a button becomes permanently disabled once clicked. How ...

Exclude all .js files from subdirectories in SVN

In my typescript project, I am looking to exclude all generated JavaScript files in a specific folder from SVN. Is there a convenient command or method to achieve this for all files within the directory? ...

Tips on sorting through an array using Angular 11 and data

I'm working on a subpage that contains a large amount of detailed data in the form of thousands of records. I want to filter this data based on the "id" from my route, which is also included in the dataset. However, I've run into some difficultie ...

Building a single-page app optimized for mobile viewing with Foundation framework

Currently facing an issue with the scaling of the viewport on certain mobile devices when loading new content via ng-include in our responsive website built on Foundation. The problem arises as the width of the page breaks, leading to horizontal scrolling. ...

Using *ngIf to verify the presence of an attribute

Currently working with Angular2 and trying to implement a condition to display something. For instance, if group.permissions=Can Create File, then something should appear on the page. This is the code I have written so far: <div class="col-md-9" *ngI ...

External API data is shown in the browser console but appears as undefined on the page

Can you please lend me a helping hand? I am facing a critical issue while attempting to retrieve data from an external API using axios in NextJS (Reactjs)/TypeScript through getServerSideProps. The data fetching is successful, and the JSON is returned on t ...

Updating state of an array nested inside an object using React and ES6

I'm fairly new to Javascript and I feel like my lack of fundamental knowledge might be hindering me from solving this issue. Despite trying different approaches and reading tutorials, I can't seem to get it right. My goal is to manipulate the st ...

Looking for a method to quickly send an email via "mailto" in CSS (or any web development language) without the need to open Outlook or Apple Mail?

I'm currently in the process of developing my own website which includes a contact form with a message box. However, when I click submit or send, it redirects me to my Outlook email where all the entered data is collected. I then have to click send ag ...

The final element is always the variable that is passed into the .on() function

Trying to create an event system similar to Backbone, I have set up an object like this: var events = { 'click .one': 'fnOne', 'click .two': 'fnTwo', 'click .three': 'fnThree' } For ...

"Error: Angular component's template URL could not be located by Webpack when in production

I have a TypeScript component for an Angular 1.5 app using webpack as the build tool. The component code is as follows: import {Component} from "../../common/decorators" const app = angular.module('app'); @Component(app, { selector: 'na ...

What is the process for the Rebol programming language to independently implement an asynchronous pluggable protocol for reading

This post outlines the process of incorporating an asynchronous pluggable protocol in Rebol that can be accessed through Firefox, Internet Explorer, or the command line For instance, if I were to define the reb:// protocol, I could enter it into a browser ...

The proper way to define an event delegator's syntax

Typically, when you want to handle a button click event, you would do so like this: $(document).ready(function() { $("button").click(function() { doSomething(); }); }); However, in the scenario of an event delegator, you may need to respon ...

Using Vuetify to send a parameter from a select option to a method as a parameter

Just starting out with vuejs and encountering an issue passing parameters from a selected option to my JavaScript method. In my updateClientIsMaster method, the item is always undefined. However, when I added v-on:change="updateClientIsMaster in the & ...

Perform a series of database queries one after the other, ensuring they are completed before

Although the database queries themselves are working fine, I am facing an issue with executing them sequentially in Node. Here is an example of the queries I need to execute in order: DELETE FROM myTable; INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z); ...

Automatically encapsulate Typescript definition files within modules

There seems to be a missing tsconfig option in my setup. Here's what I'm trying to do: I'm developing an npm module, such as: export class HelloWorld { constructor(public greeting: string){} } with the following tsconfig settings: { ...

Ajax UpdateProgress not functional

How can I resolve the issue where my AJAX UpdateProgress bar in ASP.NET is not running when executing a query in the correct format upon button click? Any solutions or help would be greatly appreciated. <html xmlns="http://www.w3.org/1999/xhtml"> ...

Is it possible to track unsuccessful email deliveries using MailApp?

In my Google Script program, I incorporate MailApp in the following manner: MailApp.sendEmail(AddressStringGlobal,EMailSubjectProperLanguageGlobal,"",{htmlBody: EMailBody}); The issue arises when I encounter a bad email address in my data set, causing my ...

How can I use JavaScript to create a drop-down menu that only appears after selecting the previous one?

<div class="row"> <div class="col-md-4"> <label for="selectCustomers">Customer Select</label> <select class="form-control pointer" name="tableCustomers" id=" ...

The data-tooltip feature displays information as [Object object]

There seems to be an issue with displaying text in the data-tooltip. Instead of showing the intended message, it is displaying [Object object]. import React from "react"; import { FormattedMessage } from "react-intl"; const translate = (id, value={}) = ...