Example JS File – DOM-based routing

Another interesting structure for WordPress theme JS is to use DOM-based routing, where custom JS code can be placed in the common function (output everywhere), or output on particular pages based on body class. It’s important to note that in the example file, body classes containing a dash should be changed to use an underscore.

/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
* ======================================================================== */
(function ($) {
var Whitespace = {
common: {
init: function () {
// Run everywhere.
},
finalize: function () {
// Run everywhere. Loaded last.
}
},
home: {
init: function () {
// Run on page with body class `home`.
}
},
code_snippets: {
init: function () {
// Run on page with body class `code-snippets` (change - to _)
}
}
};
var util = {
fire: function (func, funcname, args) {
var namespace = Whitespace;
funcname = (funcname === undefined) ? 'init' : funcname;
if (func !== '' && namespace[func] && typeof namespace[func][funcname] === 'function') {
namespace[func][funcname](args);
}
},
loadEvents: function () {
util.fire('common');
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function (i, classnm) {
util.fire(classnm);
});
util.fire('common', 'finalize');
}
};
$(document).ready(util.loadEvents);
})(jQuery);
view raw global.js hosted with ❤ by GitHub

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *