$.urlchange

$.urlchange() triggers custom events when the URL changes. This makes it easy to build URL-driven applications.

Suppose we have buttons that sort based on “City” or “Sales”. These are usually bound directly to DOM events like this:

<!-- DO NOT DO THIS -- this example shows a BAD practice -->
<button class="sort">City</button>
<button class="sort">Sales</button>
<script>
  $('.sort').on('click', function(e) { action($(this).text()) })
</script>

Problem: In the example above, the sort is lost when the page is reloaded.

Solution: DOM events should not trigger actions directly. DOM events should change the URL like this:

<button href="?_sort=City" class="urlfilter" target="#">City</button>
<button href="?_sort=Sales" class="urlfilter" target="#">Sales</button>
<script>
  $('body').urlfilter()
</script>

Now, changes in the URL should trigger actions:

$(window)
  .on('#?city', function(e, city) { action(city) })   // Listen to #? events
  .urlchange()                                        // Enable these events

Examples:

$.urlchange events