Categories
Uncategorized

Simplifying Web Components

Vanilla JS is becoming quite powerful the past 5-10 years. I keep going back to it instead of using fancy frameworks.

I fell in love with AngularJs (v1) back in the day because it was so simple to add code to pages. Then Angular 2+ requires a cli and 20+ files just to make “hello, world!”

Vanilla JS web components seemed really complex at first, and they can be. Shadow Doms, page shifts when rendering, and all that. But they don’t have to be!

You don’t need a shadow DOM. You don’t need to create your elements inside your custom element. You don’t need to isolate your styles. You can, but I don’t want to most of the time.

Here is an example of a simple “hello, world” component. Most articles would have you make a shadow dom, build the component elements inside the component, and have its own styling. But this works, too: I put the elements in the main content, and any existing styling styles them, and of course you can add your own styling with CSS selectors e.g. hello-world > textarea . In the example below, I’ve added no styling; what you see on this page is what it inherits from WordPress.

They would also have you make the inputs and outputs their own reusable web components, have the input emit events for the component to catch then act on other child elements. Or, do like me and just grab the existing elements and add the event listener there for simplicity.

<!doctype html>
<hello-world>
    <textarea>Jim</textarea>
    <textarea readonly></textarea>
</hello-world>

<script>
    class HelloWorld extends HTMLElement {
        connectedCallback() {
            document.addEventListener('DOMContentLoaded', () => {
                this.input = this.querySelector('textarea:nth-of-type(1)');
                this.output = this.querySelector('textarea:nth-of-type(2)');
                this.input.addEventListener('input', () => { this.render(); });
                this.render();
            });
        }
        render() {
            this.output.value = `Hello, ${this.input.value}!`;
        }        
    }
    window.customElements.define('hello-world', HelloWorld);
</script>




By Jim Nelson

Hi, I’m Jim. I’ve owned computers since 1979 and have been an IT professional since 1994. I've been running my own public web servers since 2005.

This site is intended to provide useful, practical answers to challenges you have.