- Web Components are the new upcoming standard in Front end world.
- We can create Custom Elements Using Web Component.
- Polymer is a Polyfill library for Web Component development.It is developed and manged by Google.
- Polymer library can be downloaded from the following link:-
- Polymer library has two JavaScript file platform.js and polymer.js .
- platform.js : This script file is the poly-fill for web component feature.This platform file will be removed when the Web Component feature is fully supported.It acts as a layer which will get reduced in coming time as the latest browser supports the features of Web Component.
- plymer.js : This script file has all the code to support to develop a polymer based custom element.
- In this Demo,”We will create custom button using polymer library“.
- The demo project has below code structure.
- The Custom button We are creating is ts-button. This button has an attribute btnLabel for showing the displayable text.This can be used as below code in index.html file.
<!doctype html>
<html>
<head>
<title>Polymer Element Demo: Custom Button</title>
<script src="components/platform/platform.js"></script>
<link rel="import" href="components/ts-button/ts-button.html">
</head>
<body>
<ts-button btnLabel="Click Me"></ts-button>
<br/><br/>
<ts-button btnLabel="Go"></ts-button>
<br/><br/>
<ts-button btnLabel="Download"></ts-button>
</body>
</html>
- The definition of this ts-button is present inside ts-button.html code.In this code a custom element is defined in polymer-element tag.It has 3 different part style,template and script tag. As name suggested style block has all the CSS relates styling about the component.template has all the HTML template code for the custom component.script tag has all the javaScript code related to the custom element like event callback.
<link rel="import" href="../polymer/polymer.html">
<polymer-element name="ts-button" attributes="btnLabel">
<template>
<style>
#tsButton{
background-color:seagreen;
color: white;
padding: 10px;
border: none;
cursor: pointer;
min-width: 100px;
}
#tsButton.active{
background-color:lightseagreen;
color: lightgrey;
}
</style>
<button on-click="{{toggleMe}}" id="tsButton">{{btnLabel}}</button>
</template>
<script>
Polymer({
toggleMe: function() {
this.$.tsButton.classList.toggle('active');
}
});
</script>
</polymer-element>
- The output will look like below screenshot.
- When the button is clicked it is bounded with toggleMe() function which toggle the active class.Below screenshot shows the ClickMe and Go button clicked.
- The Firebug inspection of the above output is listed below.
- Code for this demo can be downloaded from this link.