Building a Pager Web Component - Part 1: Basic Custom Element
Following on from my last post, Getting into Web Components, I’m going to do a series of posts that cover building a pager web component. The component will have links to navigate through pages and text to display what page we are on. Hopefully, we will end up with something like this:
Referencing the component
Before we build our component, let’s reference it on the page. First we need to think of a name for our component. The name must contain a hypen - let’s go for “x-pager”. Let’s also have attributes for the current page and total number of pages. So, our referencing markup could be:
<x-pager page="1" page-count="5"></x-pager>
Defining the custom element
In order to define the custom element, we need to register it by using document.registerElement(elementName, options)
. In our case the call is:
document.registerElement('x-pager', {prototype: Proto});
where Proto
is the prototype for the component which we can create using Object.create(HTMLElement.prototype)
. The final thing we will do in this post is to generate some markup in the component which is achieved using createdCallback()
on the component’s prototype. The full listing for our component at this stage is:
<!DOCTYPE html>
<html>
<head> </head>
<body>
<h1>my app</h1>
<x-pager page="1" page-count="5"></x-pager>
<script>
(function() {
var Proto = Object.create(HTMLElement.prototype);
Proto.createdCallback = function() {
var html = "";
html = html + "<div>";
html = html + "<a href='#' title='Go to the first page'>first</a>";
html =
html + "<a href='#' title='Go to the previous page'>previous</a>";
html = html + "<a href='#' title='Go to the next page'>next</a>";
html = html + "<a href='#' title='Go to the last page'>last</a>";
html = html + "<span>page x of y</span>";
html = html + "</div>";
this.innerHTML = html;
};
document.registerElement("x-pager", { prototype: Proto });
})();
</script>
</body>
</html>
At this stage our component looks like below. We’ll tidy this up a bit in the next post.