(Photograph by Kenny Louie / Flickr)
An thrilling characteristic of the HTML specification is creating customized HTML components. These let you create your individual HTML components together with their very own JavaScript API. This may be helpful when constructing interfaces with reused parts all through an software.
Free trial on Treehouse: Do you wish to study extra about HTML and front-end programming? Click on right here to strive a free trial on Treehouse.
On this article you’re going to learn to create your individual HTML components and outline a JavaScript API for them.
Let’s get began.
Methods to Create Customized Parts
The doc.customElements.outline()
methodology is used to create a customized HTML aspect. This ought to be handed because the title of your customized aspect together with an (non-compulsory) object that defines the API.
Within the following instance we merely create a brand new HTML aspect referred to as <x-treehouse>
after which add it to the web page.
var XTreehouseElement = doc.customElements('x-treehouse');
doc.physique.appendChild(new XTreehouseElement());
This is able to add the next HTML to the tip of the <physique>
aspect:
<x-treehouse></x-treehouse>
The title of your customized aspect should comprise a splash (-) so when the browser parses your code, it will possibly decide between customary and customized HTML components. This additionally implies that you gained’t encounter issues if a brand new HTML aspect is launched that makes use of the identical title as your customized aspect.
Making a JavaScript API For Your Ingredient
You possibly can outline a JavaScript API in your customized aspect that consists of numerous strategies and properties. To do that, begin by creating a brand new JavaScript object. This may be achieved utilizing the Object.create()
methodology. Passing HTMLElement.prototype
to this methodology will create an object with the usual set of strategies and properties accessible to HTML components.
var XTreehouseProto = Object.create(HTMLElement.prototype);
You possibly can then outline your customized strategies on this new object, as proven under.
XTreehouseProto.good day = operate() {
alert('Howdy!');
}
To outline a property in your customized aspect you need to use the Object.defineProperty()
methodology. The primary parameter ought to be your prototype object; the second is the title of the property; and the third ought to be an object describing the conduct of that property. That is the place you may set a default worth in addition to specify whether or not the property is writable or read-only.
Object.defineProperty(XTreehouseProto, 'badges', {
worth: 20,
writable : true
});
When you’ve outlined the API in your customized aspect, you want to name doc.registerElement()
. Use the title of your customized aspect as the primary parameter, after which cross in an object with a property named prototype
. The worth of this property ought to be set to the prototype object you created earlier.
var XTreehouseElement = doc.customElements('x-treehouse', {
prototype: XTreehouseProto
});
When you’ve registered your customized aspect, you may create a brand new occasion of the aspect and add it to the web page.
var xtreehouse = new XTreehouseElement();
doc.physique.appendChild(xtreehouse);
The strategies and properties you outlined earlier may be accessed simply as you’d on some other HTML aspect.
xtreehouse.good day();
var badges = xtreehouse.badges;
Extending Present Parts
In addition to creating your individual customized components, you can even use the registerElement()
methodology to increase the performance of present HTML components. Let’s lengthen the <img>
aspect to create a variation for displaying thumbnail photographs.
You begin by making a prototype object as we did earlier than. This time, nevertheless, you wish to copy the prototype object of the aspect you might be extending. On this case, that would be the HTMLImageElement
.
var ThumbImageProto = Object.create(HTMLImageElement.prototype);
Subsequent you outline a operate for the createdCallback
, which is fired when the aspect is created. (Extra on callbacks is within the subsequent part.) Right here we will set the width and top of the picture.
ThumbImageProto.createdCallback = operate() {
this.width="100";
this.top="100";
};
You can too outline customized strategies and properties as earlier than.
ThumbImageProto.changeImage = operate() {
this.src="https://weblog.teamtreehouse.com/new-image.jpg";
};
When extending an present aspect, you want to add the extends
property to your choices object within the name to doc.registerElement()
. This property ought to be set to the title of the aspect you might be extending.
var ThumbImage = doc.customElements('thumb-img', {
prototype: ThumbImageProto,
extends: 'img'
});
To make use of your customized aspect, now you can specify an is
attribute on the aspect that you’ve prolonged. Setting the worth of this attribute to the title of your customized aspect will inform the browser that this <img>
aspect ought to use the API outlined for thumb-img
.
<img is="thumb-img">
Customized Ingredient Callback Strategies
There are numerous callbacks that you could pay attention for when creating and managing your customized components.
createdCallback
– Known as when a customized aspect is created.attachedCallback
– Known as when a customized aspect is inserted into the DOM.detachedCallback
– Known as when a customized aspect is faraway from the DOM.attributeChangedCallback(attrName, oldValue, newValue)
– Known as when an attribute on a customized aspect modifications.
You specify features for these callbacks on the prototype object that’s handed to doc.registerElement()
.
var XTreehouseProto = Object.create(HTMLElement.prototype);
XTreehouseProto.createdCallback = operate() {}
XTreehouseProto.attachedCallback = operate() {}
XTreehouseProto.detachedCallback = operate() {}
XTreehouseProto.attributeChangedCallback = operate(attrName, oldValue, newValue) {}
var XTreehouse = doc.customElements('x-treehouse', { prototype: XTreehouseProto });
Customized Parts with Shadow DOM
The true energy of customized components turns into clear when you consider how they can be utilized alongside Shadow DOM. This makes it very easy to create reusable interface parts.
On this part we’re going to have a look at an instance of how you need to use customized components and Shadow DOM to create an interface element for displaying merchandise in an online retailer. The concept right here is that an internet developer can simply create new merchandise by including a single line of HTML to their markup. The knowledge wanted to show the product is contained inside data-
attributes on the customized aspect.
<x-product data-name="Product Identify" data-img="picture.png" data-url="http://instance.com"></x-product>
We’ll begin by create a brand new prototype object based mostly off of HTMLElement.prototype
.
// Create a brand new object based mostly of the HTMLElement prototype
var XProductProto = Object.create(HTMLElement.prototype);
Subsequent we have to arrange a operate for createdCallback
. That is the place we’ll create the <img>
and <a>
components which can be chargeable for displaying the product. I’ll present you the code first after which stroll you thru it.
// Arrange the aspect.
XProductProto.createdCallback = operate() {
// Create a Shadow Root
var shadow = this.createShadowRoot();
// Create an img aspect and set it is attributes.
var img = doc.createElement('img');
img.alt = this.getAttribute('data-name');
img.src = this.getAttribute('data-img');
img.width="150";
img.top="150";
img.className="product-img";
// Add the picture to the Shadow Root.
shadow.appendChild(img);
// Add an occasion listener to the picture.
img.addEventListener('click on', operate(e) {
window.location = this.getAttribute('data-url');
});
// Create a hyperlink to the product.
var hyperlink = doc.createElement('a');
hyperlink.innerText = this.getAttribute('data-name');
hyperlink.href = this.getAttribute('data-url');
hyperlink.className="product-name";
// Add the hyperlink to the Shadow Root.
shadow.appendChild(hyperlink);
};
Right here we begin by creating a brand new Shadow Root. In case you’re not accustomed to utilizing the Shadow DOM, you would possibly wish to try my earlier publish. We then create an <img>
aspect and set its alt
, src
, top
, and width
attributes utilizing the data specified on the x-product
aspect.
Be aware: Contained in the callback operate, this
refers back to the customized aspect in your markup.
Subsequent we add the <img>
aspect to the shadow root and create a brand new <a>
aspect. Once more we set the attributes on the aspect utilizing data from the data-
attributes on the customized aspect. To complete up we add the <a>
aspect we simply created to the shadow root.
Now we have to register the customized aspect. Name doc.registerElement()
passing in x-product
because the aspect title, and specifying the XProductProto
object because the prototype.
// Register the brand new aspect.
var XProduct = doc.customElements.outline('x-product', {
prototype: XProductProto
});
That concludes all of the JavaScript code that’s wanted to get this demo working. Let’s add a little bit of CSS to fashion the product objects.
x-product {
show: inline-block;
float: left;
margin: 0.5em;
border-radius: 3px;
box-shadow: 0 1px 3px rgba(0,0,0,0.3);
font-family: Helvetica, arial, sans-serif;
-webkit-font-smoothing: antialiased;
}
x-product::shadow .product-img {
cursor: pointer;
background: #FFF;
margin: 0.5em;
}
x-product::shadow .product-name {
show: block;
text-align: heart;
text-decoration: none;
colour: #08C;
border-top: 1px stable #EEE;
font-weight: daring;
padding: 0.75em 0;
}
To show a product, we simply want so as to add an <x-product>
aspect to the HTML markup. The product knowledge is about utilizing the data-name
, data-img
, and data-url
attributes. When the web page hundreds, the browser will acknowledge these as customized components and hearth the createdCallback
occasion for every of them.
<x-product data-name="Ruby" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/ruby.png" data-url="http://instance.com/1"></x-product>
<x-product data-name="JavaScript" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/javascript.png" data-url="http://instance.com/2"></x-product>
<x-product data-name="Python" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/python.png" data-url="http://instance.com/3"></x-product>
That’s it! You’ve now created a demo software that makes use of customized components and shadow DOM to show a collection of merchandise.
Take a look at the demo to see this in motion.
Be aware: This demo requires Shadow DOM, which is just supported in Chrome Canary.
Browser Assist for Customized HTML Parts
Google Chrome (model 33+) and Opera are the one browsers with help for customized components for the time being. Nonetheless, there’s a nice polyfill accessible from the Polymer mission that may add help for customized components to different browsers. The x-tags polyfill maintained by Mozilla can also be very helpful.
Obtain the Polymer CustomElements Polyfill
You possibly can verify to see if the person’s browser helps customized components by on the lookout for the registerElement()
customElements.outline();methodology on the doc
object.
if ('registerElement' in doc) {
// Supported.
} else {
// Not supported.
}
Closing Ideas
On this publish you’ve discovered find out how to create customized HTML components to be used inside your internet purposes. You’ve additionally seen find out how to use customized components alongside different applied sciences like Shadow DOM to construct wealthy front-end internet purposes.
Customized components promise to offer internet builders the power to increase the net platform to raised meet their wants. Being a part of the net parts suite, customized components additionally play properly with different applied sciences reminiscent of Shadow DOM and HTML templates. There’s little doubt in my thoughts that the introduction of internet parts marks an enormous leap ahead within the improvement of front-end internet purposes. The extra I find out about this suite of applied sciences, the extra excited I get!
What do you consider customized components? Are you planning to make use of them in your tasks? Share your ideas within the feedback.
Helpful Hyperlinks
(Photograph by Kenny Louie / Flickr)
An thrilling characteristic of the HTML specification is creating customized HTML components. These let you create your individual HTML components together with their very own JavaScript API. This may be helpful when constructing interfaces with reused parts all through an software.
Free trial on Treehouse: Do you wish to study extra about HTML and front-end programming? Click on right here to strive a free trial on Treehouse.
On this article you’re going to learn to create your individual HTML components and outline a JavaScript API for them.
Let’s get began.
Methods to Create Customized Parts
The doc.customElements.outline()
methodology is used to create a customized HTML aspect. This ought to be handed because the title of your customized aspect together with an (non-compulsory) object that defines the API.
Within the following instance we merely create a brand new HTML aspect referred to as <x-treehouse>
after which add it to the web page.
var XTreehouseElement = doc.customElements('x-treehouse');
doc.physique.appendChild(new XTreehouseElement());
This is able to add the next HTML to the tip of the <physique>
aspect:
<x-treehouse></x-treehouse>
The title of your customized aspect should comprise a splash (-) so when the browser parses your code, it will possibly decide between customary and customized HTML components. This additionally implies that you gained’t encounter issues if a brand new HTML aspect is launched that makes use of the identical title as your customized aspect.
Making a JavaScript API For Your Ingredient
You possibly can outline a JavaScript API in your customized aspect that consists of numerous strategies and properties. To do that, begin by creating a brand new JavaScript object. This may be achieved utilizing the Object.create()
methodology. Passing HTMLElement.prototype
to this methodology will create an object with the usual set of strategies and properties accessible to HTML components.
var XTreehouseProto = Object.create(HTMLElement.prototype);
You possibly can then outline your customized strategies on this new object, as proven under.
XTreehouseProto.good day = operate() {
alert('Howdy!');
}
To outline a property in your customized aspect you need to use the Object.defineProperty()
methodology. The primary parameter ought to be your prototype object; the second is the title of the property; and the third ought to be an object describing the conduct of that property. That is the place you may set a default worth in addition to specify whether or not the property is writable or read-only.
Object.defineProperty(XTreehouseProto, 'badges', {
worth: 20,
writable : true
});
When you’ve outlined the API in your customized aspect, you want to name doc.registerElement()
. Use the title of your customized aspect as the primary parameter, after which cross in an object with a property named prototype
. The worth of this property ought to be set to the prototype object you created earlier.
var XTreehouseElement = doc.customElements('x-treehouse', {
prototype: XTreehouseProto
});
When you’ve registered your customized aspect, you may create a brand new occasion of the aspect and add it to the web page.
var xtreehouse = new XTreehouseElement();
doc.physique.appendChild(xtreehouse);
The strategies and properties you outlined earlier may be accessed simply as you’d on some other HTML aspect.
xtreehouse.good day();
var badges = xtreehouse.badges;
Extending Present Parts
In addition to creating your individual customized components, you can even use the registerElement()
methodology to increase the performance of present HTML components. Let’s lengthen the <img>
aspect to create a variation for displaying thumbnail photographs.
You begin by making a prototype object as we did earlier than. This time, nevertheless, you wish to copy the prototype object of the aspect you might be extending. On this case, that would be the HTMLImageElement
.
var ThumbImageProto = Object.create(HTMLImageElement.prototype);
Subsequent you outline a operate for the createdCallback
, which is fired when the aspect is created. (Extra on callbacks is within the subsequent part.) Right here we will set the width and top of the picture.
ThumbImageProto.createdCallback = operate() {
this.width="100";
this.top="100";
};
You can too outline customized strategies and properties as earlier than.
ThumbImageProto.changeImage = operate() {
this.src="https://weblog.teamtreehouse.com/new-image.jpg";
};
When extending an present aspect, you want to add the extends
property to your choices object within the name to doc.registerElement()
. This property ought to be set to the title of the aspect you might be extending.
var ThumbImage = doc.customElements('thumb-img', {
prototype: ThumbImageProto,
extends: 'img'
});
To make use of your customized aspect, now you can specify an is
attribute on the aspect that you’ve prolonged. Setting the worth of this attribute to the title of your customized aspect will inform the browser that this <img>
aspect ought to use the API outlined for thumb-img
.
<img is="thumb-img">
Customized Ingredient Callback Strategies
There are numerous callbacks that you could pay attention for when creating and managing your customized components.
createdCallback
– Known as when a customized aspect is created.attachedCallback
– Known as when a customized aspect is inserted into the DOM.detachedCallback
– Known as when a customized aspect is faraway from the DOM.attributeChangedCallback(attrName, oldValue, newValue)
– Known as when an attribute on a customized aspect modifications.
You specify features for these callbacks on the prototype object that’s handed to doc.registerElement()
.
var XTreehouseProto = Object.create(HTMLElement.prototype);
XTreehouseProto.createdCallback = operate() {}
XTreehouseProto.attachedCallback = operate() {}
XTreehouseProto.detachedCallback = operate() {}
XTreehouseProto.attributeChangedCallback = operate(attrName, oldValue, newValue) {}
var XTreehouse = doc.customElements('x-treehouse', { prototype: XTreehouseProto });
Customized Parts with Shadow DOM
The true energy of customized components turns into clear when you consider how they can be utilized alongside Shadow DOM. This makes it very easy to create reusable interface parts.
On this part we’re going to have a look at an instance of how you need to use customized components and Shadow DOM to create an interface element for displaying merchandise in an online retailer. The concept right here is that an internet developer can simply create new merchandise by including a single line of HTML to their markup. The knowledge wanted to show the product is contained inside data-
attributes on the customized aspect.
<x-product data-name="Product Identify" data-img="picture.png" data-url="http://instance.com"></x-product>
We’ll begin by create a brand new prototype object based mostly off of HTMLElement.prototype
.
// Create a brand new object based mostly of the HTMLElement prototype
var XProductProto = Object.create(HTMLElement.prototype);
Subsequent we have to arrange a operate for createdCallback
. That is the place we’ll create the <img>
and <a>
components which can be chargeable for displaying the product. I’ll present you the code first after which stroll you thru it.
// Arrange the aspect.
XProductProto.createdCallback = operate() {
// Create a Shadow Root
var shadow = this.createShadowRoot();
// Create an img aspect and set it is attributes.
var img = doc.createElement('img');
img.alt = this.getAttribute('data-name');
img.src = this.getAttribute('data-img');
img.width="150";
img.top="150";
img.className="product-img";
// Add the picture to the Shadow Root.
shadow.appendChild(img);
// Add an occasion listener to the picture.
img.addEventListener('click on', operate(e) {
window.location = this.getAttribute('data-url');
});
// Create a hyperlink to the product.
var hyperlink = doc.createElement('a');
hyperlink.innerText = this.getAttribute('data-name');
hyperlink.href = this.getAttribute('data-url');
hyperlink.className="product-name";
// Add the hyperlink to the Shadow Root.
shadow.appendChild(hyperlink);
};
Right here we begin by creating a brand new Shadow Root. In case you’re not accustomed to utilizing the Shadow DOM, you would possibly wish to try my earlier publish. We then create an <img>
aspect and set its alt
, src
, top
, and width
attributes utilizing the data specified on the x-product
aspect.
Be aware: Contained in the callback operate, this
refers back to the customized aspect in your markup.
Subsequent we add the <img>
aspect to the shadow root and create a brand new <a>
aspect. Once more we set the attributes on the aspect utilizing data from the data-
attributes on the customized aspect. To complete up we add the <a>
aspect we simply created to the shadow root.
Now we have to register the customized aspect. Name doc.registerElement()
passing in x-product
because the aspect title, and specifying the XProductProto
object because the prototype.
// Register the brand new aspect.
var XProduct = doc.customElements.outline('x-product', {
prototype: XProductProto
});
That concludes all of the JavaScript code that’s wanted to get this demo working. Let’s add a little bit of CSS to fashion the product objects.
x-product {
show: inline-block;
float: left;
margin: 0.5em;
border-radius: 3px;
box-shadow: 0 1px 3px rgba(0,0,0,0.3);
font-family: Helvetica, arial, sans-serif;
-webkit-font-smoothing: antialiased;
}
x-product::shadow .product-img {
cursor: pointer;
background: #FFF;
margin: 0.5em;
}
x-product::shadow .product-name {
show: block;
text-align: heart;
text-decoration: none;
colour: #08C;
border-top: 1px stable #EEE;
font-weight: daring;
padding: 0.75em 0;
}
To show a product, we simply want so as to add an <x-product>
aspect to the HTML markup. The product knowledge is about utilizing the data-name
, data-img
, and data-url
attributes. When the web page hundreds, the browser will acknowledge these as customized components and hearth the createdCallback
occasion for every of them.
<x-product data-name="Ruby" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/ruby.png" data-url="http://instance.com/1"></x-product>
<x-product data-name="JavaScript" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/javascript.png" data-url="http://instance.com/2"></x-product>
<x-product data-name="Python" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/python.png" data-url="http://instance.com/3"></x-product>
That’s it! You’ve now created a demo software that makes use of customized components and shadow DOM to show a collection of merchandise.
Take a look at the demo to see this in motion.
Be aware: This demo requires Shadow DOM, which is just supported in Chrome Canary.
Browser Assist for Customized HTML Parts
Google Chrome (model 33+) and Opera are the one browsers with help for customized components for the time being. Nonetheless, there’s a nice polyfill accessible from the Polymer mission that may add help for customized components to different browsers. The x-tags polyfill maintained by Mozilla can also be very helpful.
Obtain the Polymer CustomElements Polyfill
You possibly can verify to see if the person’s browser helps customized components by on the lookout for the registerElement()
customElements.outline();methodology on the doc
object.
if ('registerElement' in doc) {
// Supported.
} else {
// Not supported.
}
Closing Ideas
On this publish you’ve discovered find out how to create customized HTML components to be used inside your internet purposes. You’ve additionally seen find out how to use customized components alongside different applied sciences like Shadow DOM to construct wealthy front-end internet purposes.
Customized components promise to offer internet builders the power to increase the net platform to raised meet their wants. Being a part of the net parts suite, customized components additionally play properly with different applied sciences reminiscent of Shadow DOM and HTML templates. There’s little doubt in my thoughts that the introduction of internet parts marks an enormous leap ahead within the improvement of front-end internet purposes. The extra I find out about this suite of applied sciences, the extra excited I get!
What do you consider customized components? Are you planning to make use of them in your tasks? Share your ideas within the feedback.