Wednesday, December 30, 2015

on hashchange, on jQuery, on donner, on blitzen

Some coders take on large frameworks because they like some of the features provided - but some of those features can be easily duplicated in systems that have less conceptual overhead, such as jQuery.

One of those features is hash anchor driven navigation, which is pretty decent way of making a one-page-app with back button support, so long as you start with hash page control from the outset and not try to glom it on after.

All you need to do is set up a listener on the window hashchange event:
$(function() {
    $(window).bind('hashchange', hashChanged);
(remember that's the short hand for $(document).ready()... I'm not sure that it's not too concise for its own good, frankly.)

Then, your hashChanged function can do whatever it wants with the new value:
function hashChanged(){
    var hash = window.location.hash.slice(1);

You can set that hash value programmatically:
window.location.hash = 'someValue';
or you can do it in the DOM, like in a link:
<a href="#someOtherValue">let's go</a>

This is the kind of high-transparency, low-conceptual-and-code overhead coding style I tend to go to for small applications, and maybe even medium-sized ones. Obviously, the actual guts of your hashChanged function can get complex and tangled if you let it, but this is a good building block to know- if you'd rather just install a nice kitchen than buy the whole house.

No comments:

Post a Comment