Web component custom elements

Getting started with custom elements

I wrote the first custom element using a CSS library called CSS Doodle. This is an amazing application that uses "custom elements" to create stunning CSS animations. This releases a whole new desire to figure out how the thing works under the hood. Therefore, I decided to better study web components in general, which is a topic that many people ask me to write about.

Using custom elements, we can create new HTML tags.

Before I used the CSS Doodle library, I couldn't imagine why this might be a useful thing. After all, we already have a lot of tags.

This tutorial introduces Custom Elements version 1, which is the latest version of the standard at the time of writing.

Using custom elements, we can create custom HTML tags with associated CSS and JavaScript.

It is not an alternative to frameworks such as React, Angular or Vue, but a completely new concept.

ThiswindowThe global object exposes acustomElementsEnable us to accessCustomElementRegistrypurpose.

ThisCustomElementRegistrypurpose

The object has several methods for registering custom elements and querying registered custom elements:

  • define()Used to define new custom elements
  • get()The constructor for obtaining custom elements (returnsundefinedIf it does not exist)
  • upgrade()Upgrade custom elements
  • whenDefined()Used to get the constructor of the custom element. Similar toget(), But it will return a promise, which will be resolved when the product is available.

How to create custom elements

Before we callwindow.customElements.define()Method, we must define a new HTML element by creating a new class that extends the built-in class of HTMLElement:

class CustomTitle extends HTMLElement {
	//...
}

Inside the class constructor, we will useShadow DOMAssociate custom CSS, JavaScript and HTML to our new markup.

In this way, all we will see in the HTML are our tags, but this will encapsulate many functions.

We start by initializing the constructor:

class CustomTitle extends HTMLElement {
  constructor() {
    super()
    //...
  }
}

Then we call itattachShadow()By passing the object to the HTMLElement methodmodeAttribute is set to'open'. This attribute sets the encapsulation mode of the shadow DOM. If it isopenWe can visitshadowRootThe attributes of the element. If it is closed, we cannot.

The way to do this is as follows:

class CustomTitle extends HTMLElement {
  constructor() {
    super()
    this.attachShadow({ mode: 'open' })
    //...
  }
}

You will find some examples of using the syntaxconst shadowRoot = this.attachShadow(/* ... */)But you can avoid this unless you setmodeToclosed, Because you can always refer to the object by callingthis.shadowRoot.

What we have to do now is to set its innerHTML:

class CustomTitle extends HTMLElement {
  constructor() {
    super()
    this.attachShadow({ mode: 'open' })
    this.shadowRoot.innerHTML = `
      <h1>My Custom Title!</h1>
    `
  }
}

You can add as many tags as you want, not justinnerHTMLproperty

Now, we add this newly defined element towindow.customElements:

window.customElements.define('custom-title', CustomTitle)

We can use<custom-title></custom-title>Custom elements in the page!

Note: You cannot use the auto-closing label (in other words:<custom-title />Is not allowed by the standard)

note-The dash in the tag name.We must use dashesIn the custom element. This is how we can detect built-in tags from custom tags.

Now that we have this element on the page, we can use other tags to manipulate it: use CSS and JavaScript to locate it!

Provide custom CSS for elements

In the constructor, you can pass astyleIn addition to HTML tags used to define content, tags can also include Custom Element CSS:

class CustomTitle extends HTMLElement {
  constructor() {
    super()
    this.attachShadow({ mode: 'open' })
    this.shadowRoot.innerHTML = `
      <style>
        h1 {
          font-size: 7rem;
          color: #000;
          font-family: Helvetica;
          text-align: center;
        }
      </style>
      <h1>My Custom Title!</h1>
    `
  }
}

This is the sample Custom Element we created in Codepen:

Look at the penWeb component, my custom titleBy Flavio Copes (@flaviocopes) InCipher pen.

Tech Wiki Online!