write single-page apps with a single callback to handle pushState events


pushState callback with a #hash fallback


Given some html with elements #foo, #bar, and #baz:

    <div id="foo">
      foo foO fOo fOO Foo FoO FOo FOO
      <div><a href="/bar">bar</a></div>
    <div id="bar">
      bar baR bAr bAR Bar BaR BAr BAR
      <div><a href="/baz">baz</a></div>
    <div id="baz">
      baz baZ bAz bAZ Baz BaZ BAz BAZ
      <div><a href="/foo">foo</a></div>
    <script src="bundle.js"></script> 

Now turn each of the divs into pages with their own routes. Note that this module doesn't update the link callbacks for you. You'll need to handle that for yourself.

var divs = {
    foo: document.querySelector('#foo'),
    bar: document.querySelector('#bar'),
    baz: document.querySelector('#baz')
var singlePage = require('single-page');
var showPage = singlePage(function (href) {
    Object.keys(divs).forEach(function (key) {
    var div = divs[href.replace(/^\//, '')];
    if (div) show(div)
    else show(
    function hide (e) { = 'none' }
    function show (e) { = 'block' }
var links = document.querySelectorAll('a[href]');
for (var i = 0; i < links.length; i++) {
    links[i].addEventListener('click', function (ev) {

You'll need to have a server that will serve up the same static content for each of the pushState routes. Something like this will work:

var http = require('http');
var ecstatic = require('ecstatic')(__dirname);
var server = http.createServer(function (reqres) {
    if (/^\/[^\/.]+$/.test(req.url)) {
        req.url = '/';
    ecstatic(req, res);

Now when you go to http://localhost:5000 and click around, you'll see /foo, /bar and /baz in the address bar when you click links, even though you're not reloading the page.


var singlePage = require('single-page')

Fire cb(href) at the start and whenever the page navigation changes so you can update the page contents accordingly.

Navigate to href, firing the callback passed to singlePage.


With npm do:

npm install single-page

Use browserify do bundle this module into your application.