jQuery DOM Router

For a while I’ve been using my own fork of the Roots (now Sage) starter theme for most of my WordPress projects. The theme is packed with awesome twists of the WordPress we all know and love. We have the Theme Wrapper, which sticks with the D.R.Y. (Don’t Repeat Yourself) principles. And one thing I especially fell in love with, a DOM-based router.

What is DOM-based Routing?

The DOM-based Routing is based on a concept by Paul Irish from 2007. In short terms it fires javascript based on classes set to the body-element.

This is clean enough for most people, but I always the syntax felt a bit cluttered, both in Roots and the snippet from Paul Irish.

Enter jQuery DOM Router

I decided to make a jQuery plugin which works in the same way as Roots’ DOM-router, but has, in my eyes, a much cleaner syntax, and moves the logic out of the main script file. It shall be called jQuery DOM Router.

One major difference from what Roots’/Paul’s method does, is that jQuery DOM Router works on live changes to the `<body>` element. As soon as you add a class to your body element, the JavaScript you’ve set up will fire.

How does it work?

First of all you include jQuery.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

Then include the plugin code.

<script src="dist/jquery.dom-router.min.js"></script>

Now you can go ahead and call the plugin. Simply use the name of the class to fire on as the name of a property in an object passed to the plugin. If something is to be fired on no matter what, you create a property named `common`. Class names with dashes are read with underscores by the plugin, so a class of `big-cakes-for-you` would be `big_cakes_for_you`.

$(document).router({
    classname: function() {
        // fire your js when the body has class "classname" when the page loads
    },
    common: function() {
        // code put inside the common property will be executed on all page loads
    }
});

And I mentioned, it responds to live changes. So, check out this example.

<html>
  	<head>
    	<title>My Awesome DOM Router</title>
  	</head>
  
  	<body class="home">
    
		<h1>jQuery DOM Router Example</h1>
		
		<button id="add">Add class</button>
		<div id="container">
		</div>

		<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
	

  	</body>
</html>

See the Pen XbZjrQ by Tor Morten Jensen (@tormjens) on CodePen.

In this example only the javascript under “common” and “home” are executed, which is understandable as we only have the “home”-class on our body. But looks what happens when we press the “Add class”-button. The code under “laters” is fired. Note that code is only fired once during each request, so if you add the class, remove and then add it again, it will have no effect other than the first time.

jQuery DOM Router is on Github. Enjoy!

A developer with a passion for new technology, agile methods and smart solutions.