Skip to content

Instantly share code, notes, and snippets.

@curran
Last active December 4, 2015 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curran/c1fc921813f33092a2ef to your computer and use it in GitHub Desktop.
Save curran/c1fc921813f33092a2ef to your computer and use it in GitHub Desktop.
X Foo Button

A demonstration of how to use webcomponents.js to build a simple WebComponent. This is a copy of the example presented in this tutorial Custom Elements, with slight modifications so it works on bl.ocks.org.

According to the tutorial Custom Elements, the following lifecycle callbacks are supported:

  • createdCallback() is called when a custom element is created.
  • attachedCallback() is called when a custom element is inserted into a DOM subtree.
  • detachedCallback() is called when a custom element is removed from a DOM subtree.
  • attributeChangedCallback(attributeName) is called when a custom element's attribute value has changed

This example only uses the createdCallback() method. These methods are documented in more detail in javascripture: CustomElementPrototype.

Built with blockbuilder.org

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/0.7.18/webcomponents.min.js"></script>
<style>
x-foo {
font-size: 12em;
}
</style>
</head>
<body>
<x-foo></x-foo>
<script>
var XFooButtonPrototype = Object.create(HTMLButtonElement.prototype);
XFooButtonPrototype.createdCallback = function() {
this.textContent = "I'm an x-foo button!";
};
var XFooButton = document.registerElement('x-foo', {
prototype: XFooButtonPrototype
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment