portsoc / custom-elements

Web Components

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Custom Elememts

An introduction to Templates, Shadow DOM, Web Components and thus: Custom Elements.

Templates

In template0.html we define a web page that includes a template. The template is cloned into a variable called cloned.

The user is prompted to use the console to manipulate the contents of the cloned template and then append it to the page.

In template1.html we define a web page with three parts: a button b1, an empty main element, and a template identified as t1.

When the button is clicked, the template is cloned and its contents are added to main.

The cloneNode function takes one parameter: deep which should be true if a deep copy of the template is desired (i.e. containing all text and element subnodes). This is likely to be the desired behaviour for templates.

In template2.html we extend the example by altering the content of the template which now reads <p>The time now is <em>not specified</em>.</p>.

When the template is inserted into the page the current time replaces the words "not specified" in the template.

In template2.html we highlight that a page can contain multiple templates by comnbining the first two examples. Each template must have a unique ID in order to be selectable.

Shadow DOM

In shadow1.html we define a web page with two parts: a button b1, and a main element which contains two sections, one of which has the id example.

This example introduces the concept of shadow DOM. An instance of shadow DOM can contain elements just like the browser's normal DOM, and can be attached to the document just like any other element.

When the button is clicked, we create an instance of shadow DOM using the attachShadow method. This replaces all the content of the example element that is being attached to. We then add new content to the shadow DOM and it appears in place of the original paragraphs.

attachShadow takes an object parameter which must include a mode property, which can be open or closed. A closed shadow DOM can be accessed and altered only by scripts that are contained within it.

In shadow2.html we add a stylesheet to the shadow DOM. The stylesheet contains one rule, setting all paragraphs to have red text. The stylesheet only affects the paragraphs in the shadow DOM.

In shadow3.html we see that we can use templates to populate shadow DOM elements.

In shadow4.html the difference between an open and closed shadow DOM is illustrated. Two shadow DOMs are created, one open, one closed. The first can be written to by the JS, setting its innerHTML, the second cannot, and an error is thrown when the write is attemped.

Web Components

About

Web Components