Web Component Hello World

by Richard Hunter

HTML

<foo-component bg-color="yellow"></foo-component>
<foo-component bg-color="pink"/>

<h1>blah</h1>
<p>dfdf</p>

JavaScript

class FooComponent extends HTMLElement {
  constructor() {
    super();
    
    const shadow = this.attachShadow({mode: 'open'});
    const span = document.createElement('span');
    const backgroundColor = this.getAttribute('bg-color');
    span.innerHTML = `
    	<div>
      	<style>
        	:host {
          	background: ${backgroundColor};
            display: block;
            padding: 10px;
          }
        	h1 {
          	color: red;
            font-family: helvetica;
          }
          
          p {
          	font-family: courier;
          }
        </style>
      	<h1>Hello world</h1>
        <p>it's the end of the world as we know it</p>
      </div>
    `;
    shadow.appendChild(span);
  }
  
  connectedCallback() {
  	console.log('connected');
  }
}

customElements.define('foo-component', FooComponent);