I'm trying the example from google developer site and I'm getting Error: "TypeError: Illegal constructor.
What's wrong and How to fix it?
class FancyButton extends HTMLButtonElement {
constructor() {
super(); // always call super() first in the ctor.
this.addEventListener('click', e => this.drawRipple(e.offsetX,e.offsetY));
}
// Material design ripple animation.
drawRipple(x, y) {
let div = document.createElement('div');
div.classList.add('ripple');
this.appendChild(div);
// div.style.top = `${y - div.clientHeight/2}px`;
// div.style.left = `${x - div.clientWidth/2}px`;
div.style.backgroundColor = 'currentColor';
div.classList.add('run');
div.addEventListener('transitionend', e => div.remove());
}
}
customElements.define('fancy-button', FancyButton, {extends: 'button'});
let button = new FancyButton();
button.textContent = 'Fancy button!';
button.disabled = true;
Blink, the web engine that currently implements Custom Element v1 (in Chrome v53+ for example) only supports autonomous custom elements: see open Blink bug.
If you want to define customized built-in elements (i.e. <button>
extension), you'll need to use a polyfill like the one from Web Reflection.
Alternatly, you can still use the Custom Element v0 syntax (document.registerElement
).
Update #3
Since october 2018, they work natively with Chrome 67+ and Firefox 63+ :-)
class F_BTN extends HTMLButtonElement{
constructor(){
super(); // must call constructor from parent class
this.addEventListener(...);
.... // etc.
}
}
now help customElements.define to know what is registering
customElements.define("f-btn",F_BTN,{extends:'button'});
// <button></button> -- not TagName which is BUTTON
// HTMLAnchorElement -> 'a' ; HTMLInputElement -> 'input'
u can create elements now like:
<body>
....
<f-btn>BTN_NAME</f-btn>
...
</body>
or
var elm = new F_BTN(...options);
// F_BTN = customElements.get('f-btn') // in case F_BTN is out of scope
The problem is elm = document.createElement('f-btn')
doesn't work. That is why I use smth. like
_E = function (name, opt) {
var $;
switch (true) {
case (name === '' || !name):
{
$ = document.createElement('div');
}
break; // create div
case (!name.indexOf('<')):
{
$ = document.createElement('div');
$.innerHTML = name;
$ = $.firstElementChild;
}
break;
default:
var c = window.customElements.get(name);
if(c){
return new c(opt);
} else {
document.createElement(name);
}
}
if (opt)
$.innerHTML = opt;
return $;
};
var elm1 = _E('f-btn'); parent.appendChild(elm1);