Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend HTMLElement prototype

I'm trying to extend the prototype of the HTMLElement object in main.ts, so that I can use it throughout my whole Angular 6 project.

But I get the 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 am I doing wrong?

Where do I need to put this code so that can I make this method available everywhere?

Do you also see a possibility to make this code cleaner?

like image 876
Kode Bryant Avatar asked Mar 05 '23 16:03

Kode Bryant


1 Answers

You need to add a definition to be merged with the original interface in which you define the extra function to be added to HTMLElement

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

// Will now 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 the code is in a module you need 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;
like image 181
Titian Cernicova-Dragomir Avatar answered Mar 09 '23 06:03

Titian Cernicova-Dragomir