I would like to make a web component that simply allows me to run a simple JavaScript function. i.e. it would function the two following codes would act the same way:
<body>
<div id="sample"></div>
<script> createSample(); </script>
</body>
and
<body>
<my-web-component></my-web-component>
</body>
I've tried reading some online guides to creating web components, but I am relatively new to working in JavaScript in praticular and web environments in general, so it mostly went over my head. Is there any simpele way to do what I described? Thank you for the help!
You're almost there, to expand on your implementation we can use basic Javascript to create custom HTML components using the HTMLElement interface. Also, take a look in the HTML living standard specification for some more examples and implementations.
As an example, we can first define the new custom component and its functionality in Javascript (This can be done in the tag in your HTML or in a separate external js file).
class MyComponent extends HTMLElement {
connectedCallback() {
this.innerHTML = `<h1>Hello world</h1>`;
}
}
customElements.define('my-web-component', MyComponent);
<body>
<my-web-component></my-web-component>
</body>
And lastly, define the component in your HTML file, don't forget to include the js file if you're using an external file to put the Javascript snippet in. When the Javascript snippet gets executed on page load, it creates the custom component and renders it to the page.