Skip to content
Advertisement

WebComponent that extends HTMLButtonElement is not calling constructor() and connectedCallBack()

I’m trying to create a web component button but when I add it in HTML the constructor() function is never being called.

class MyButton extends HTMLButtonElement {
  title = "";
  constructor({ title }) {
    super();
    this.title = title;
    this.addEventListener("click", (e) => this.rippe(e.offsetX, e.offsetY));
  }

  rippe(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("transitioned", (e) => div.remove());
  }

  connectedCallback() {
    this.innerHTML = this.title;
  }
}
window.customElements.define("my-button", MyButton, { extends: "button" });
my-button {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #12c2e9;
  background: -webkit-linear-gradient(to right, #12c2e9, #c471ed, #f64f59);
  background: linear-gradient(to right, #12c2e9, #c471ed, #f64f59);
  border-radius: 28px;
  border: none;
  height: 56px;
  width: 268px;
  outline: none;
  color: #fff;
  font-size: 16px;
  font-family: -apple-system, BlinkMacSystemFont, sans-serif;
}

my-button:hover {
  filter: contrast(90%);
}

my-button:active {
  filter: contrast(85%);
}
<!DOCTYPE html>
<html lang="pt">
  <head title="test page">
    <script type="text/javascript" src="./my_button.js"></script>
    <link rel="stylesheet" type="text/css" href="./my_button.css" />
  </head>
  <meta charset="UTF-8" />
  <title>web components</title>
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <body>
    <my-button title="Wab components!"></my-button>
  </body>
</html>

I’m facing some problems:

1- The constructor() is not being called so my event listener is not being added to the element;
2- connectedCallback () lifecycle is not being called too, so my button is not getting the title passed as a parameter;

Why this is happening and how I can fix this?

constructor() is only being called if i instantiate my custom element and append in `body:

let popup = new PopUpInfo();
document.body.appendChild(popup);

But I would use my custom selector “my-button” in HTML instead of appending it.

Advertisement

Answer

Re: from comments

That link is to the HTMLButtonElement That is a standard element supported by all Browsers.

There are 2 different flavored Web Components:
details see Web Components : extending native elements

  • Autonomous Elements (extend from HTMLElement)
  • Customized Built-In Elements (extend from any Element)

But Apple/WebKit will not implement the latter as stated in 2016:

https://github.com/WICG/webcomponents/issues/509

Advertisement