Skip to content

Instantly share code, notes, and snippets.

@Grinderofl
Created November 16, 2011 06:22
Show Gist options
  • Select an option

  • Save Grinderofl/1369415 to your computer and use it in GitHub Desktop.

Select an option

Save Grinderofl/1369415 to your computer and use it in GitHub Desktop.
jQuery: Autohash extension
(function ($) {
/**
* jQuery extension to parse hash (#) in url,
* fill in values of input boxes with the specific ID's,
* and automatically update the values on address bar by
* monitoring the change/keyup events.
*/
$.fn.autohash = function () {
// This extension is chainable
return this.each(function () {
// Gets the window hash and get rid of the # in front of it
var hash = window.location.hash.substr(1, window.location.hash.length);
// Simple things, breaking it down into array
var array = hash.split("&");
// Making sure the element currently modified is cached
var element = $(this);
// Keyup is the default event the extension fires on
element.bind('keyup', function () {
var hash2 = window.location.hash.substr(1, window.location.hash.length);
var array2 = hash2.split("&");
var result = Array();
// Boolean to know whether the element is already found
var set = false;
/**
* Simple loop to go through each element in tbe hash array,
* check if it's name matches the element's ID, if so
* its value in the array is changed and then joined later,
* unless the length is 0, in which case it can be removed from the hash
*/
$.each(array2, function(i, value) {
var split = value.split("=");
if (split[0] == element.attr('id')) {
split[1] = element.val();
set = true;
}
if (split[1] != undefined && split[1].length > 0) {
result[result.length] = split.join("=");
}
});
// If element can't be found, it'll be added here
if (!set && element.val().length) {
result[result.length] = element.attr('id') + "=" + element.val();
}
// Finally the address bar text is changed, with an IE hack, as per usual.
if (result.join("&").length > 2)
window.location.hash = result.join("&");
else {
if ("pushState" in history)
history.pushState("", document.title, window.location.pathname);
else
window.location.hash = "";
}
});
// Bind the change event to the previous function
element.bind('change', function () {
element.keyup();
});
// Upon loading, the values from hash tag are set
// The change event is also triggered, if anything was listening to those
$.each(array, function (i, value) {
var split = value.split("=");
if (split[0] == element.attr('id')) {
element.val(split[1]);
element.change();
}
});
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment