AngularJS and Angular 2+: a Detailed Comparison

This article compares the major differences between the the original AngularJS and Angular 2+. If you’re currently stuck with an AngularJS project and not sure whether you should make the jump, this article should help you get started.
In recent years, we’ve seen Angular grow tremendously as a framework and as a platform for developing single page applications (SPAs) and progressive web apps (PWAs). AngularJS was built on top of the idea that declarative programming should be used for building the views. This required decoupling the DOM manipulation from the business logic of the application and the approach had many benefits on its own.
However, AngularJS had many shortcoming in terms of performance and how things worked under the hood. Hence, the development team spent a year rewriting the code from scratch and finally released Angular 2 in late 2016. Most developers felt that Angular 2 was a different platform that had very little resemblance to the original AngularJS.
So let’s compare and contrast AngularJS and Angular 2+.
Frameworks in AngularJS and Angular 2
AngularJS follows the traditional MVC architecture that comprises a model, a view and a controller.

Controller: the controller represents how user interactions are handled and binds both the model and the view.
Views: the view represents the presentation layer and the actual UI.
Model: the model is an abstract representation of your data.

Some developers are of the opinion that AngularJS follows MVVM pattern that replaces the Controller with a View-Model. A View-Model is a JavaScript function that’s similar to that of the controller. What makes it special is that it synchronizes the data between a view and a model. The changes made to a UI element automatically propagate to the model and vice versa.
The following diagram shows how various AngularJS pieces are connected together.

You can read more about AngularJS’s architecture on the official documentation page.
Angular, on the other, hand has a component-based architecture. Every Angular application has at least one component known as the root component. Each component has an associated class that’s responsible for handling the business logic and a template that represents the view layer. Multiple, closely related components can be stacked together to create a module and each module forms a functional unit on its own.

As you can see in the figure, the component is bound to the template. Components are composed using TypeScript classes and templates are attached to them using @Component annotations. Services can be injected into a component using Angular’s dependency injection subsystem. The concept of modules in Angular is drastically different from that of the AngularJS modules. An NgModule is a container for defining a functional unit. An NgModule can comprise components, services and other functions. The modular unit can then be imported and used with other modules.
All the Angular concepts are better explained at
Templates in AngularJS and Angular 2
In AngularJS the template is written using HTML. To make it dynamic, you can add AngularJS-specific code such as attributes, markups, filters and form controls. In addition, it supports the two-way data binding technique mentioned earlier. The following code snippet demonstrates the use of directives and double curly brackets within the template:

<!– Body tag augmented with ngController directive –>
<body ng-controller=”MyController">
<inpu#t ng-model="foo" value="bar">
<!– Button tag with ngClick directive –>
<!– Curly bracket is a template binding syntax –>
button ng-click="changeFoo()"></button>
<script src="angular.js"></script>

In Angular, AngularJS’s template structure was reworked and lots of new features were added to the templates. The primary difference was that each component had a template attached to it. All the HTML elements except <html>, <body>, <base>, and <script> work within the template. Apart from that, there are features such as template binding, template interpolation, template statements, property binding, event binding and two-way binding. Built-in attribute directives like NgClass, NgStyle and NgModel and built-in structural directives such as NgIf, NgForOf, NgSwitch are also part of the template.
Continue reading %AngularJS and Angular 2+: a Detailed Comparison%


How to Build a File Upload Form with Express and Dropzone.js

Let’s face it, nobody likes forms. Developers don’t like building them, designers don’t particularly enjoy styling them and users certainly don’t like filling them in.
Of all the components that can make up a form, the file control could just be the most frustrating of the lot. A real pain to style, clunky and awkward to use and uploading a file will slow down the submission process of any form.
That’s why a plugin to enhance them is always worth a look, and DropzoneJS is just one such option. It will make your file upload controls look better, make them more user-friendly and by using AJAX to upload the file in the background, at the very least make the process seem quicker. It also makes it easier to validate files before they even reach your server, providing near-instananeous feedback to the user.
We’re going to take a look at DropzoneJS in some detail; show how to implement it and look at some of the ways in which it can be tweaked and customized. We’ll also implement a simple server-side upload mechanism using Node.js.
As ever, you can find the code for this tutorial on our GitHub repository.
Introducing DropzoneJS
As the name implies, DropzoneJS allows users to upload files using drag n’ drop. Whilst the usability benefits could justifiably be debated, it’s an increasingly common approach and one which is in tune with the way a lot of people work with files on their desktop. It’s also pretty well supported across major browsers.
DropzoneJS isn’t simply a drag n’drop based widget, however; clicking the widget launches the more conventional file chooser dialog approach.
Here’s an animation of the widget in action:

Alternatively, take a look at this, most minimal of examples.
You can use DropzoneJS for any type of file, though the nice little thumbnail effect makes it ideally suited to uploading images in particular.
To summarize some of the plugin’s features and characteristics:

Can be used with or without jQuery
Drag and drop support
Generates thumbnail images
Supports multiple uploads, optionally in parallel
Includes a progress bar
Fully themeable
Extensible file validation support
Available as an AMD module or RequireJS module
It comes in at around 33Kb when minified

Browser Support
Taken from the official documentation, browser support is as follows:

Chrome 7+
Firefox 4+
IE 10+
Opera 12+ (Version 12 for MacOS is disabled because their API is buggy)
Safari 6+

There are a couple of ways to handle fallbacks for when the plugin isn’t fully supported, which we’ll look at later.
The simplest way to install DropzoneJS is via Bower:
bower install dropzone

Alternatively you can grab it from Github, or simply download the standalone JavaScript file — though bear in mind you’ll also need the basic styles, also available in the Github repo.
There are also third-party packages providing support for ReactJS and implementing the widget as an Angular directive.
First Steps
If you’ve used the Bower or download method, make sure you include both the main JS file and the styles (or include them into your application’s stylesheet), e.g:


An Introduction to Functional JavaScript

You’ve heard that JavaScript is a functional language, or at least that it’s capable of supporting functional programming. But what is functional programming? And for that matter, if you’re going to start comparing programming paradigms in general, how is a functional approach different from the JavaScript that you’ve always written?
Well, the good news is that JavaScript isn’t picky when it comes to paradigms. You can mix your imperative, object-oriented, prototypal, and functional code as you see fit, and still get the job done. But the bad news is what that means for your code. JavaScript can support a wide range of programming styles simultaneously within the same codebase, so it’s up to you to make the right choices for maintainability, readability, and performance.
Functional JavaScript doesn’t have to take over an entire project in order to add value. Learning a little about the functional approach can help guide some of the decisions you make as you build your projects, regardless of the way you prefer to structure your code. Learning some functional patterns and techniques can put you well on your way to writing cleaner and more elegant JavaScript regardless of your preferred approach.
Imperative JavaScript
JavaScript first gained popularity as an in-browser language, used primarily for adding simple hover and click effects to elements on a web page. For years, that’s most of what people knew about it, and that contributed to the bad reputation JavaScript earned early on.
As developers struggled to match the flexibility of JavaScript against the intricacy of the browser document object model (DOM), actual JavaScript code often looked something like this in the real world:
[code language=”js"]
var result;
function getText() {
var someText = prompt("Give me something to capitalize");
alert(result.join(" "));
function capWords(input) {
var counter;
var inputArray = input.split(" ");
var transformed = "";
result = [];
for (counter = 0; counter < inputArray.length; counter++) { transformed = [ inputArray[counter].charAt(0).toUpperCase(), inputArray[counter].substring(1) ].join(""); result.push(transformed); } }; document.getElementById("main_button").onclick = getText; [/code] So many things are going on in this little snippet of code. Variables are being defined on the global scope. Values are being passed around and modified by functions. DOM methods are being mixed with native JavaScript. The function names are not very descriptive, and that’s due in part to the fact that the whole thing relies on a context that may or may not exist. But if you happened to run this in a browser inside an HTML document that defined a <button id="main_button">, you might get prompted for some text to work with, and then see the an alert with first letter of each of the words in that text capitalized.
Imperative code like this is written to be read and executed from top to bottom (give or take a little variable hoisting). But there are some improvements we could make to clean it up and make it more readable by taking advantage of JavaScript’s object-oriented nature.
Continue reading %An Introduction to Functional JavaScript%


6 jQuery Form Wizard Plugins

A jQuery Form Wizard is a jQuery plugin that assists with the creation of forms with some sort of form flow (without refreshing your page). For example, if you had a large form for entering user data, you could use a form wizard to divide it into a series of related steps. This has the advantage of not overwhelming users with a really long form and also giving them some indication of their progress as they enter their information.
In this post we list 6 of our favorite jQuery form wizards, examine their different features and finally look at a couple of paid options, as well as how to create your own. This isn’t intended to be an exhaustive list, but if you are looking for a jQuery form wizard, then hopefully this will point you in the right direction.

This popular post was updated on 30.08.2017. Broken / abandoned plugins were removed from the list and new plugins were added to reflect features people were asking for in the comments.

1. jQuery Steps
jQuery Steps is a smart UI component which allows you to easily create wizard-like interfaces. This plugin groups content into sections for a more structured and orderly page view. It has a plethora of features, such as async content loading, state persistence (it saves your input between steps) and transition effects between sections. It can be installed via NuGet or bower and has a well-documented and feature-rich API.

Homepage | GitHub | Demo
2. jQuery Smart Wizard
Smart Wizard is a flexible and heavily customizable jQuery step wizard plugin with Bootstrap support. It is easy to implement and gives a neat and stylish interface for your forms, checkout screen, registration steps etc. Its features include theme support (with various themes included), URL navigation and step selection and the ability to dynamically hide or disable steps. It can be installed via npm, bower or composer and has a well-documented and feature-rich API.

Homepage | GitHub | Demo
3. formToWizard
This lightweight plugin turns any webform into multi-step wizard with jQuery, whereby every form

is turned into a separate step with forward and back buttons. It doesn’t have nearly as many features as the previous two plugins, but does integrate with the jQuery validation plugin to provide validation functionality. It is a single file (so you can just grab it off GitHub and go) and if JavaScript is unavailable, it degrades gracefully.

GitHub | Demo
Continue reading %6 jQuery Form Wizard Plugins%


Your Site without JavaScript

This post was originally published on and reposted here with the author’s permission. If you’re interested in taking Calibre for a spin, you can start a free 14-day trial today.
There are plenty of reasons why the presence of JavaScript (what it does, how it works, and how heavy it is) needs to be considered a little more thoughtfully.
Web traffic today is made up of more than 50% mobile devices, of these devices, many operate under extremely volatile network connections—loading scripts alone in less than 10 seconds is nigh on impossible in many situations.
If you’re working on a single page app, with no reasonable content-only fallbacks, this can be far more damaging than you may think—users will be watching a white screen, with partial content, for a long time.

According to Google’s DoubleClick, when comparing sites that load in 5 seconds to sites that load in 19 seconds, the faster sites had 70% longer average session lengths, 35% lower bounce rates and 25% higher ad viewability than their slower counterparts.

Performance is important, there’s no doubting that, but what common negative impacts does JavaScript have on our sites? How are we currently evaluating performance?
Let’s Have a Brief (but Constructive) Look at the Cost of JavaScript
When commonly auditing the performance impacts of JavaScript, we look at:

The number of render-blocking scripts present on the page
How long scripts take to download, and the amount of data transferred

But what we’re often missing is what happens thereafter…
Once the device has downloaded the scripts, they must be parsed, converted to bytecode, compiled and then executed.
Parse and compile time are two reasons why the same site that works great on your $3000 MacBook, feels kind of janky on a 2-year-old smartphone.

The above graphic compares Chrome parse/compile times on a regular desktop browser, verses a low power mobile device. This graphic is taken from Addy Osmani’s excellent article titled “JavaScript Start-up Performance".

Let’s say, as an experiment, that we removed all scripts to establish a performance baseline, to answer the question "Just how fast could this be?".
Calibre exists to make it trivial for teams to have better visibility to more areas of performance and user-experience, so in the spirit of that, you can now run a direct comparison of your site with, or without JS—as a Test profile.

💥Now you’re testing with and without JavaScript
I enabled the ability to disable scripts, and run a few test runs against popular global news sites, both with, and without JavaScript.
Continue reading %Your Site without JavaScript%


How to Create a QR Code Reader for Your Mobile Website

The barcode and QR code have modernized our shopping and searching experience. Customers carrying smartphones can now pick up a product anywhere in the world, scan its barcode or its QR code using one of the many free phone apps and find out its lowest price as well as where it can be bought.

Companies like Walmart and Amazon have embraced this technique to draw customers to their online and offline stores using their phone app. Other companies like Fedex and UPS allow customers to scan the codes on packages using a phone app, instead of needing to manually type in long lists of characters.
If the users of your mobile website have a need to type in long codes like activation codes or they like to look up specific products on your website based on a model number printed in a magazine or advertisement, then you too can take advantage of QR codes to eliminate the frustration of tiny keyboards and spare them the need to double check for errors.
QR Code Scanning with your Mobile Website
You don’t need a native phone app to scan QR codes —it’s quite simple to create your own QR code reader. Your website running on a smartphone equipped with a camera and running a little JavaScript can do the same trick.
Here is a demo of a text field with an in-built QR button. In addition to being able to type text into the field, users can also click a button to activate the camera.

Browser Requirements:
Your users need to be on an iPhone running iOS 6 or higher or an Android phone running Android 3.0 or higher. Other devices have not been tested.

See the Pen Bare QR reader demo by SitePoint (@SitePoint) on CodePen.

If you are on a supported device, go ahead and click it. Depending on your phone, it will either launch the camera immediately or ask you whether to open the camera or browse your photo library. On unsupported devices, the browser will open up a regular file explorer window.
If you don’t have a QR code handy to scan, here is one that shows the first 8 digits of Pi.

Creating the QR Code Reader
The magic starts with the file upload element. We spruce it up with an accept attribute which tells the browser that we only want images and we give it a capture attribute which means we want the input to be captured now, as opposed to uploading an old picture from the phone’s memory.


JavaScript Design Patterns: The Observer Pattern

In JavaScript, there is a problem that comes up often. You need a way to update parts of a page in response to certain events, with the data these provide. Say, for example, user input that you then project into one or many components. This leads into a lot of push-and-pull in the code to keep everything in sync.
This is where the observer design pattern can help — it enables one-to-many data binding between elements. This one-way data binding can be event driven. With this pattern, you can build reusable code that solves for your specific needs.
In this article, I’d like to explore the observer design pattern. It will help you solve a common problem you see in client-side scripting. That is one-to-many, one-way, and event-driven data binding. It is a problem that comes up often when you have many elements that must be in sync.
I’ll use ECMAScript 6 to illustrate the pattern. Yes, there will be classes, arrow functions, and constants. Feel free to explore these topics on your own if you are not already familiar. I’ll use parts of ES6 that introduce syntactic sugar only, so it is portable with ES5 if need be.
And I’ll use Test-Driven-Development (TDD) to work on the pattern. This way you have a way knowing how each component is useful.
The new language features in ES6 make for some succinct code. So, let’s get started.
The Event Observer
A high-level view of the pattern looks like this:

├── subscribe: adds new observable events

├── unsubscribe: removes observable events
└── broadcast: executes all events with bound data

After I flesh out the observer pattern I’ll add a word count that uses it. The word count component will take this observer and bring it all together.
To initialize the EventObserver do:
class EventObserver {
constructor() {
this.observers = [];

Start with an empty list of observed events, and do this for every new instance. From now on, let’s add more methods inside EventObserver to flesh out the design pattern.
The Subscribe Method
To add new events do:
subscribe(fn) {

Grab the list of observed events and push a new item to the array. The list of events is a list of callback functions.
One way to test this method in plain JavaScript is as follows:
// Arrange
const observer = new EventObserver();
const fn = () => {};

// Act

// Assert
assert.strictEqual(observer.observers.length, 1);

I use Node assertions to test this component in Node. The exact same assertions exist as Chai assertions too.
Note the list of observed events consists of humble callbacks. We then check the length of the list and assert that the callback is on the list.
The Unsubscribe Method
To remove events do:
unsubscribe(fn) {
this.observers = this.observers.filter((subscriber) => subscriber !== fn);

Continue reading %JavaScript Design Patterns: The Observer Pattern%


Grab Our Free Printable Functional JavaScript Cheat Sheet

Functional programming (FP) has become a hot topic in the JavaScript community. It’s being touted as a great way of building scalable and maintainable applications and we’re staring to see many of its core principles incorporated into libraries and frameworks — for example stateless functional components in React.
Continue reading %Grab Our Free Printable Functional JavaScript Cheat Sheet%


Quick Tip: Getting Started with Headless Chrome in Node.js

Oftentimes in our line of work we need to be able to replicate a user journey repeatedly to make sure that our pages are offering a consistent experience as we make changes to our site. Critical to being able to accomplish this consistently and conveniently are libraries that allow us to script these types of tests, so that we can run assertions against them and maintain documentation around the results. Enter headless browsers: command line tools that provide you with the ability to script a user’s interactions across your site programmatically and capture the results to use in tests.
Many of us have been using PhantomJS, CasperJS, and other tools for years to do just this. But, as often is with love, our hearts can be bequeathed to another. As of Chrome 59 (60 for Windows users), Chrome ships with its own headless browser. And, although it doesn’t currently offer support for Selenium, it uses Chromium and the Blink engine, i.e. it is simulating an actual user experience in Chrome.
As ever, the code for this article can be found on our GitHub repo.
Run Headless Chrome From the Command Line
Running Headless Chrome from the command line is relatively easy. On a Mac, you can set an alias for Chrome and run using the —headless command line parameter
alias chrome=”/Applications/Google\\ Chrome”
chrome –headless –disable-gpu –remote-debugging-port=9090

On Linux, it’s even easier:
google-chrome –headless –disable-gpu –remote-debugging-port=9090

–headless: Runs without a UI or display server dependencies
–disable-gpu: Disables GPU hardware acceleration. This is temporarily needed for now.
–remote-debugging-port: Enables remote debug over HTTP on the specified port.

You can also interact with the page you are requesting, for example to print document.body.innerHTML to stdout you can do:
google-chrome –headless –disable-gpu –dump-dom

If you’re curious what else is possible, a full list of parameters can be found here.
Running Headless Chrome in Node.js
The focus of this article however, is not the command line, rather running Headless Chrome in Node.js. To do this, we’re going to need the following modules:

chrome-remote-interface: JavaScript API provides a simple abstraction of commands and notifications.
chrome-launcher: this allows us to launch Chrome from within Node across multiple platforms.

Continue reading %Quick Tip: Getting Started with Headless Chrome in Node.js%


Using Polymer in WordPress: Build a Custom Google Maps Component

Web components are a set of standards for creating custom, reusable HTML elements. Polymer is an open-source JavaScript library for building web applications using web components. Created by those clever folks at Google, it provides a number of additional features over vanilla web components and when used with a polyfill, supports the latest version of all major browsers.
In this tutorial I’m going to show you how easy it is to make use of web components and Polymer in WordPress. I’m going to start by showing you how to integrate Polymer into your WordPress install, then I’m going to demonstrate how to add a working Google Maps component to your site’s side bar. This might be useful for any site (e.g. that of a restaurant) which needs to provide visitors with directions to their premises.
After reading, you’ll be able to employ this technique on a site of your own. And you’ll not be limited to a Google Map widget, you’ll be able to choose from the wide range of pre-made components, or even write your own.
As ever, all of the code for this tutorial is available in a GitHub repository.
Why Polymer?
As native support for web components is growing ever better, you might be forgiven for asking if Polymer is still relevant. The short answer to that question is Yes!
Polymer does make use of a variety of web component polyfills—which will hopefully one day full by the wayside—but it is a lot more than that. Polymer is a wrapper around the web components API that allows us to develop and implement new components at a much greater speed than we would otherwise be able. It offers various additional features over vanilla web components, such as one-way and two-way data binding, computed properties and gesture events. It comes with a very polished CLI which can be used for such tasks as scaffolding out a project, running tests, or running a local server, and it can make use of a wide range of pre-built elements, such as the much loved material design elements library.
In short, Polymer is still very relevant. It is a powerful framework, which is used in production by large companies such as USA Today, Coca Cola and Electronic Arts.
Setting Up WordPress
Before we start, we need to setup our environment that is going to be running WordPress. For this tutorial, I’ll be using the ScotchBox Vagrant VM, equipped with some pre-installed tools to kickstart your WordPress installation.

If you have WordPress installed already, or would prefer to use a different method, you can skip this bit. If you need a bit of help with the setup, but don’t want to go the vagrant route described below, try Googling “install WordPress locally" and looking for an up-to-date tutorial.

We start of by making sure that Git, Vagrant and Virtual Box are installed on our system. We can then clone the GitHub repo with ScotchBox’s pre-populated Vagrantfile.
git clone sitepoint-wp-polymer

Now we are ready to run vagrant up. After our machine has booted, we have to remove the default /public/index.php static file and install WordPress.
cd sitepoint-wp-polymer/public
rm index.php
git clone .

Now we have to make a duplicate of the wp-config-sample.php file. Name it wp-config.php.
cp wp-config-sample.php wp-config.php

and edit the following values:
// wp-config.php

// …

define(‘DB_NAME’, ‘scotchbox’);
define(‘DB_USER’, ‘root’);
define(‘DB_PASSWORD’, ‘root’);

// …

Now you are ready to fire up your browser and visit You will be prompted to enter the admin account credentials and site title. Feel free to fill these out as you see fit.

Adding the SitePoint Base Theme
So we’ve got WordPress set up, now we need a theme. Out of the box, this will be the Twenty Seventeen theme, but this is pretty generic and includes much more than you normally need. A good alternative here, is to use the SitePoint WordPress base theme.
This theme was created in response to the question "What would the perfect WordPress base theme look like?". Its features include:

No fat. No cruft. Speedy.
Minimal design. It’s your job to make it pretty.
No ‘cute’ features you never actually use.
SEO friendly to its core.
Super Mobile-friendly.
100% Open Source and free to use.

The SitePoint WordPress base theme is a great starting point for new projects. It’s mobile friendly, easy to use and 100% free. To follow along with the rest of tis tutorial, head over to the theme’s homepage and download it now.
And while you’re there, you might like to check out the suite of paid themes SitePoint offers, too. These are all built on top of the base theme and include an ecommerce theme, restaurant theme, portfolio theme, business theme and construction theme.
After downloading SitePoint WordPress base theme, unzip it and copy/paste to thewp-content/themes folder. Then create a new folder called sitepoint-base-child, in wp-content/themes. In that directory create a style.css file and a functions.php file.
cd wp-content/themes/
mkdir sitepoint-base-child
cd sitepoint-base-child
touch functions.php style.css

Open up style.css and copy this into it:
Theme Name: SitePoint Base Child
Author: Almir B.
Author URI:
Template: sitepoint-base
Version: 1.0.0
Text Domain: ab-sitepoint-base

And into functions.php:
Themes from the main side menu, and click Activate under, Sitepoint Base Child theme.

Including Polymer in WordPress
Now that’s done, we have to install Polymer with bower. Make sure you are in the public/wp-content/themes/sitepoint-base-child folder, and then run:
bower init

You can answer with default answer to every question. Next we need to install the dependencies:
bower install –save Polymer/polymer#^2.0.0 PolymerElements/paper-input#2.0-preview

This will install Polymer and the paper-input component, so that we can have a fancy material designed input component out of the box. It is important to use the #2.0-preview tag for the paper input and also for the Google Map element later, as it will not work with the latest version of Polymer (version 2.0) otherwise.
In order to user Polymer, we have to include it using an HTML import, and we will also include the polyfill for web components, so as to support older browsers.
Head to the functions.php file in the child theme, and add an enqueue to the existing enqueue function.

add_action( ‘wp_enqueue_scripts’, ‘sp_theme_enqueue_styles’ );
function sp_theme_enqueue_styles() {
wp_enqueue_style( ‘parent-style’, get_template_directory_uri() . ‘/style.css’ );
wp_enqueue_script( ‘polymer’, get_stylesheet_directory_uri() . ‘/bower_components/webcomponentsjs/webcomponents-lite.js’ );

WordPress does not have an enqueue function for enqueueing HTML imports, but we can hook into the wp_head hook which outputs into the <head> element of the page.

add_action( ‘wp_enqueue_scripts’, ‘sp_theme_enqueue_styles’ );
function sp_theme_enqueue_styles() {
wp_enqueue_style( ‘parent-style’, get_template_directory_uri() . ‘/style.css’ );
wp_enqueue_style( ‘polymer’, get_stylesheet_directory_uri() . ‘/bower_components/webcomponentsjs/webcomponents-lite.min.js’ );

add_action( ‘wp_head’, ‘include_polymer_elements’ );
function include_polymer_elements() {

<link rel="import"
href="<?php echo get_stylesheet_directory_uri() ?>/bower_components/polymer/polymer.html">
<link rel="import"
href="<?php echo get_stylesheet_directory_uri() ?>/bower_components/paper-input/paper-input.html">

That’s all we needed to start using Polymer elements in WordPress. Now let’s create a WordPress widget so we can take this out for a test ride.
Registering a Widget
In order to create a new widget, we will create a new child class from the WP_Widget class and then register it with the widgets_init hook.
Create a new folder in your child theme, name it lib, and add it a file named sitepoint-map-widget.php.
mkdir lib
cd lib
touch sitepoint-map-widget.php

Copy the following into that file:
// lib/sitepoint-map-widget.php

class SitepointMapWidget extends WP_Widget {

function __construct() {
// Instantiate the parent object
parent::__construct( false, ‘Google Paper Input’ );

function widget( $args, $instance ) {
echo ‘<paper-input raised always-float-label label="Floating label"></paper-input>’;

All we did here is create a new child class of WP_Widet and called the parent constructor in order to give the widget a custom name. Additionally, the widget function is the one that does the actual output. For now, we will simply output a <paper-input> element, which is an element from the paper-input-elements collection.
Last but not least, we need to include this new PHP file at the top of our functions.php file:
// functions.php
require_once( ‘lib/sitepoint-map-widget.php’ );

// …

and then register a widget at the end of the file:
// functions.php

// …

add_action( ‘widgets_init’, ‘sp_register_widgets’ );
function sp_register_widgets() {
register_widget( ‘SitepointMapWidget’ );

Now we can go into the admin dashboard of WordPress. From the main menu, go into Appearance > Widgets, and there you should see a widget named Google Paper Input on the left.
Drag and drop it into the Main Sidebar section to the right, above the rest of the default widgets from the SitePoint Base theme.

Now you can visit the homepage, and on the right side right above the search box, you will see a material design input with a label.

And thus we have concluded Polymer’s Hello, World! example. We’ve covered a lot of ground already—installing Polymer, integrating it with WordPress and including a sample widget, all in just a few lines of code—but in the next section we will take this further and implement our Google Map component.
Continue reading %Using Polymer in WordPress: Build a Custom Google Maps Component%