The JavaScript blog.


routing ui libraries

State-Based Routing with abstract-state-router

Posted on .

A few months ago I wrote a custom hash URL router for a React project. We've been trying to plug in a more generalised open source router, but dealing with the state in our particular application has proved problematic. Josh Duff sent in abstract-state-router (GitHub: TehShrike/abstract-state-router, License: WTFPL, npm: abstract-state-router), a general purpose routing library that isn't tied into any specific framework. Josh had been working with Angular, but wanted to use a routing library outside of Angular projects.

This is from Josh's post about the project - Why your webapp needs a state-based router:

I'm a child of the node/npm revolution, and as such I'm pretty framework-averse. I prefer disconnected modules that solve problems that I can compose myself.

I looked for similar libraries, but the only ones I found (react-router and Ember's router) are similarly tied to their chosen rendering/templating tools.

Built with help from ArtskydJ, abstract-state-router is heavily inspired by ui-router, intended to be used with whatever templating library you like. At the time of this writing, renderers have been set up for Ractive.JS, Riot, and virtual-dom - and it's not too difficult to implement new ones with your favorite template/dom manipulation library.

The API uses ideas from ui-router and Express: route names are parsed using ui-router's dot notation, and routes are parsed with a fork of path-to-regexp.

Here's a quick example:

var createStateRouter = require('abstract-state-router');  
var stateRouter = createStateRouter(makeRenderer, rootElement, options);

  name: 'app.tab1',
  data: {},
  route: '/tab_1',
  template: '',
  resolve: function(data, parameters, cb) {
  }, activate: function(context) {
    document.getElementById('tab').innerText = context.content

In this example, the makeRenderer option is a function that returns an object with four properties: render, destroy, getChildElement, and reset. There's an example of this in the test helpers.

Once you've set up a router, you can browse to a specific state with stateRouter.go. The way state change is handling is documented in the readme in detail, but every state change destroys DOM elements that are no longer valid, and then creates the new states.

To my knowledge abstract-state-router is unique because it focuses on state and defining routes, so it's not tied to any specific framework. Josh said he's willing to help people hook it up to specific UI libraries, so if you want to use it but aren't sure how t implement the rendering code then he may help you out!


google-maps react polymer services ui libraries

Isomorphic Google Maps, MyScriptJS

Posted on .

Isomorphic Google Maps

Ivan Starkov sent in an isomorphic Google Maps component for React (GitHub: istarkov/google-map-react, License: MIT, npm: google-map-react). It provides several useful features, including rendering any React component over maps, lazy loading of the Google Maps API, and isomorphic rendering.

By rendering maps on the server, you can improve search engine visibility, and render maps without requiring JavaScript in the browser. Naturally you could also do other cool stuff with server-side libraries that would otherwise be made difficult in the browser.

The ability to render any React component over a map means you make dynamic map features that feel very fast -- Ivan's library calculates the co-ordinates independently of Google Maps, so you can treat your React code separately instead of worrying too much about how it relates to Google Maps.

Now every object on the map can be hovered (however, you can still use css hover selectors if you want). If you try zooming out here example, you will still be able to hover on almost every map marker.

This algorithm allows you to tweak hover probability of map objects, for example making some objects "more hoverable". distance_hover example with different hover probabilities

The main example shows a map combined with fast infinite scrolling, SVG icons, and balloons made with React.


MyScript is a service for handwriting and handwritten shape recognition. Gregory Pakosz sent in some Polymer MyScript components for interacting with the service. The components are built with MyScriptJS, and they cover things like mathematical expression and text recognition.

MyScript Web Components

The demos on the MyScript Web Components homepage are interactive, so if you select the <myscript-math> example and press play you should be able to draw some equations and see the results.


ui react ES6 libraries

FluxThis Router, React Transitive Number

Posted on .

FluxThis ES6 Router

Josh Horwitz wrote in to say that FluxThis has a new router that takes advantage of ES6 syntax. It has an API that is inspired by Koa for defining routes with middleware that drops through a stack using the yield statement:

export default function (router) {  
  router.use(function *(next) {
    // do some stuff
    yield *next;
    // do some stuff after everyone else

  router.all('/user*', function *userAuthHandler(next) {
    document.title = 'User Profile';

    // perhaps do some authentication stuff?
    if (authFails()) {
      return; // short circuit the middleware chain

    yield *next;

The idea is to use middleware without using deeply nested callbacks, which the generator syntax seems to solve quite nicely.

FluxThis is a Flux implementation by the developers at AddThis.


react-transitive-number (GitHub: Lapple/react-transitive-number, License: MIT, npm: react-transitive-number) by Aziz Yuldoshev is a React component that transforms numbers into stateful counters with animations. The author has a demo that compares plain HTML with the TransitiveNumber version.

To use it, just wrap a number with a <TransitiveNumber> component. The animation looks like a tumbler from an old clock, and apparently it was inspired by Groupon's old countdown timers.


libraries ui browser dom

sdm, CSS HTML Hint

Posted on .

Simple DOM Module

Whenever I have to write real DOM code, I get a little bit of perverse pleasure out of the fact I can remember certain arcane parts of the DOM APIs. I wouldn't describe myself as a DOM expert, but after years of high-level frameworks it's easy to forget addEventListener, parentNode.removeChild, appendChild, and the fun cross-browser issues we used to have to deal with.

awalGarg sent in a small project that attempts to make DOM code more readable without having the exact same API as jQuery. It's called sdm (License: WTFPL) and it attempts to do part of what jQuery does, but only by using the standard DOM APIs without any shims.

The API is designed around two objects: $$ and $. If you want to work with multiple nodes, then use $$, otherwise for single elements use $. The methods map neatly to DOM methods:

  • getElementsByClassName: $$.cl(className [, parent = document])
  • getElementsByName: $$.nam(name [, parent = document])
  • getElementsByTagName: $$.tag(tagName [, parent = document])

There are more methods as well, including $$.data() and $$.attr.

One interesting detail is the use of $.id instead of $('#' + id). The author said it's too easy to forget the hash symbol, and I do this all the time with CSS selector APIs, so I liked the idea.

I've noticed the tendency for people who use the newer frameworks like React and Angular to want to avoid jQuery. Most of the time you don't need to manipulate or query elements (React lets you reference specific nodes, for example), but sometimes you actually need to do things outside of the framework and have to dip back into DOM programming. Naturally pulling in the entire jQuery library feels unnecessary, so smaller libraries like this are becoming interesting again.


There's a popular and lightweight tooltip library called hint.css by Kushagra Gour. It's very simple and easy to use, but doesn't support HTML in the hints. Ivan Starkov sent in css html hint (GitHub: istarkov/html-hint, License: MIT, npm: html-hint) which overcomes this limitation.

To use it, you'll need to use the right classes and markup, but it basically involves adding the hint--html class to a container with a child that has the hint__content class. The bundled CSS looks nice, so it's easy to drop into an existing project.


design interviews animation ui authors

Interview: The Future of Web Animation with Julian Shapiro

Posted on .

Developer and startup founder, Julian Shapiro, has had an impact on the JavaScript world. We've covered a few of his web development accomplishments in the past: we wrote about the launch of Julian's text manipulation library, Blast.js, in addition to the work he's best known for: Velocity.js and Velocity.js' UI pack. The Velocity JavaScript animation engine is a top-ranked library on GitHub, with users including WhatsApp, IBM, Tumblr, Yahoo! and many others.

After receiving a grant from Stripe for his work on Velocity, he also built the fascinating Libscore, the community goodwill project that helps developers compare the relative popularity of web frameworks and third-party libraries. Recently, Julian wrote Web Animation using JavaScript for Pearson.

In our interview with Julian, we address the future of web animation, and the role JavaScript might play in it.

Julian Shapiro

DailyJS: What makes animation exciting in 2015—compared to the older Web 2.0 animation libraries?

Julian: We have faster browsers today, and they're only continuing to get faster at an impressive rate. The Chrome team, in particular, also happens to be aggressively pushing to standardize browser behavior on Android. Those two factors, combined with the increasing computing power of mobile devices, means that Web animation performance will continue to improve -- even if developers' implementations stay stuck in old ways. The other predominant trend in web development performance is simply its broader awareness, along with the increased importance being placed on it. Fortunately, performance is no longer a second-class citizen in web development education and industry news outlets. With broader awareness comes broader implementation and deeper understanding of best practices. Since there is a lot of low-hanging fruit that can be picked in web performance, this too will result in significant gains in site performance and usability in the coming months.

All of this leads to a performant base web development platform upon which beautiful and fluid animations can be layered. The higher we can push animations to perform -- across all browsers and devices -- the sooner the slick motion design commonly found in mobile apps will exist without compromise on the Web.

DailyJS: What trends will we see in the future of Web animation?

Julian:We might see a wave of too-clever and overused motion design in web user interfaces. Are you familiar with those awesome-yet-crazy After Effects-produced motion design examples on Dribbble? Those will become a technical reality on web pages soon enough. Like all things, however, I think the wave will peak then collapse, and we'll settle into a happy medium of quality user experiences bolstered by motion design that doesn't detract from usability.

In terms of trends, the inevitable growth of React Native might mean we'll also see a large shift in the tooling landscape toward the React ecosystem. I wouldn't be shocked if React is the future of web programming as we know it. If this turns out to be the case, animation engines will have to follow suit or they'll otherwise become irrelevant.

DailyJS: What type of animation works best in JavaScript, and what type works best with CSS?

Julian:In terms of common interface animations, CSS is best suited for simple element state-based animation, e.g. hovering, clicking, etc. As for intricate loading sequences, JavaScript animation is typically better suited.

When it comes to more complex motion design, such as page and element scrolling, physics-based motion, and touch and drag capabilities, JavaScript is the only realistic solution. I don't foresee this dichotomy changing any time soon.


Animation may very well permanently shift toward the realm of JavaScript as the ecosystem develops. Animation is too important of a UI design component to be relegated to the minimal programming logic of CSS (as is dictated and updated on an irregular basis by a standards body). JavaScript, in contrast, inherently allows a developer to layer an infinite amount of logical control over animation, and that power will prove valuable in ways we have yet to imagine. (Browser-based VR, anyone?)

DailyJS: What animation anti-patterns should developers and designers be aware of?

Julian: Utility and elegance are the goals of all great Web animation. Great animators deliberately choose every aspect (e.g. easing, target properties, duration, and so on) of their seemingly arbitrary animation sequences -- because they want to reinforce the intentions of a UI, and that's a very calculated decision. Whimsical motion design, in contrast, is not only inconsistent, but it also appears inelegant and diverting to the user.

The sad truth is that -- while there are hundreds of tutorials on the minutiae of UI design -- there is very little education on motion design. They're both very important aspects: Whereas UI design lays the structural foundation for interacting with a web page, motion design enriches that foundation with the furnishing and decoration that make the page usable and comfortable. If you allow me to be metaphorical for a moment, furnishing is the utility that motion design serves, and decoration is the elegance it provides. Great apps leverage both utility and elegance to make the user feel like they're interacting with an interface that's living, breathing, and tangible. In contrast, an interface that's devoid of motion design reminds the user that she's simply dragging a cursor across a screen or tapping her finger on a piece of glass. In other words, a web page without motion design can make the user painfully aware of the artifice before her.

With that context out of the way, common anti-patterns include:

  • Employing one-off motion design interactions that break from convention: The less you copy motion design from existing popular apps and sites, the less familiar your interface will feel to the user, and the less confidence she'll have when using it. While there's utility in novelty, the motion design of everyday UI elements shouldn't be novel. It should be reliably obvious.

  • Allowing complex animation sequences to consume a large total duration: Developers often make the mistake of letting animations run too long, causing the user to wait needlessly. UI flourishes should never slow down the apparent speed of a page. If you have a lot of content fading into view within a larger animation sequence, ensure that both the individual animation steps and the total animation sequence duration are kept short. Don't lose track of the bigger UX picture. Since it's difficult to judge the appropriateness of your animation durations after seeing them play out dozens of times during development, a good rule of thumb is to speed up all animations by 25 percent before you push a site to production.

  • Being frivolous: Interface developers should regularly be downloading the most popular apps, playing with them extensively, and judging whether they feature animation to a greater or lesser extent than their own work does. If they feel that the apps use animation to a much lesser extent, they need to consider toning back the motion design in their UI. Simply, if a particular piece of motion design doesn't provide psychological utility to the overall experience (affordance, clarity, connection, etc.), then its inclusion should be reconsidered. Injecting motion design for its own sake leads to bloated interfaces.

  • Not experimenting: Finding the right duration, stagger, easing, and property combinations for each animation is not a skill that designers are simply born with. It's a skill that every great developer-designer has had to hone. So, remember: your first attempt at a combination of animation properties might look good, but it's probably not the best combination. You should experiment by systematically changing each factor in the motion design equation into you stumble into something sublime. Once you've found a combination you love, experiment even further. Consider cutting the duration in half, switching to a completely different easing type, or swapping out a property. Designers are often averse to repeated experimentation because they believe in the sanctity of their whimsically-derived creative nuggets of insight. But insights have relative value, so it's important to get outside of your comfort zone to see what else you can come up with. Professional developers should strive for greatness, not goodness. Greatness always entails experimentation.

I've written a lot about these theoretical aspects of motion design in my book, which also dives into the topics of animation performance and animation workflow.