JSFiddle - React, Tailwind, and code Playground
HTML
<head>
<title>test webcomponent</title>
<script src="comp.js"></script>
<script>
function myScript() {
console.log("event!");
alert ("myScript");
}
</script>
</head>
<body>
<H1>test webcomponents</H1>
<my-component id="xyz" bez="hallo" hello="myScript()"></my-component>
<script>
xyz.addEventListener("hello", function(event) {
console.log(event.detail.name);
});
</script>
</body>
JavaScript
class MyComponent extends HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({mode: 'open'});
var p=document.createElement("p");
//in connectedCallback verwenden, nicht im konstruktor!
var cap=this.getAttribute('bez');
console.log("bez="+cap);
var button=document.createElement("button");
button.innerHTML=cap;
button.addEventListener('click', () => {
console.log("click");
button.dispatchEvent(new CustomEvent("hello", {
detail: { name: "John" }
}));
});
shadow.appendChild(button);
}
/*
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue === newValue) {
return;
}
console.log(`The attribute ${name} has changed`);
}
*/
}
customElements.define('my-component',MyComponent);