Skip to content

Instantly share code, notes, and snippets.

@nfeldman
Created July 1, 2011 02:58
Show Gist options
  • Save nfeldman/1057786 to your computer and use it in GitHub Desktop.
Save nfeldman/1057786 to your computer and use it in GitHub Desktop.
Utility script for use with Drupal Menus
/**
* Utility to add a className to the menu block menu item that would be the
* current node's parent, based on the url path.
* @param {array} cores, an array containing the 1st parts of url segments
* associated with individual menu blocks where the
* index maps to the id of the menu block such that
* for a[n] there will exist an element with the id
* block-menu_block-n.
* @author Noah Feldman
* @copyright 2011
*/
// UPDATED because apparently I can't count, how embarrassing
(function (cores) {
var uri = window.location.href.split('/'),
segments = [], menu, links, link;
// cross-browser indexOf for arrays, strings, nodeLists, etc.
function indexOf(item, list) {
if (!!list.indexOf)
return list.indexOf(item);
for (var i = 0, len = list.length; i < len; i++)
if (list[i] === item) return i;
return -1;
}
// bare-bones filter implementation
function filter(list, func) {
if (list && typeof list.length != 'number')
throw TypeError('cannot iterate object that does not have a length');
for (var i = 0, len = list.length, ret = []; i < len; i++) {
var x = list[i];
func.call(null, x, i, list) && ret.push(x);
}
return ret;
}
// create an array of URL segments from the root relative URL
for (var i = 2, j = 0, len = uri.length; ++i < len; ++j)
segments[j] = uri[i];
// and figure out the ID that should match the current menu block's ID
// this was shortened to the first part of the segment as the least likely
// to change if friendly urls are tweaked...may be a false assumptio
menu = document.getElementById('block-menu_block-' + indexOf(segments[0].substring(0, segments[0].indexOf('-')), cores));
if (menu) {
// get all links beneath it
link = menu.getElementsByTagName('a');
// and winnow them down to 1 link or nothing
for (var ct = 0, len = segments.length; ct++ < len;) {
links = link;
link = filter(links, function(el) {
var t = RegExp("^" + segments[ct]),
h = el.getAttribute('href');
if (/^http/.test(h))
h = el.getAttribute('href', 2);
h = h.substring(1).split('/');
if (h[ct] && t.test(h[ct]))
return el;
});
if (link.length == 1)
return link[0].className += link[0].className ? ' active' : 'active';
}
}
}([0,0,'patient','research','professional','special','community','overview']));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment