Skip to content

Instantly share code, notes, and snippets.

@jeremyworboys
Created April 17, 2012 06:11
Show Gist options
  • Save jeremyworboys/2403838 to your computer and use it in GitHub Desktop.
Save jeremyworboys/2403838 to your computer and use it in GitHub Desktop.
jQuery: Responsive Nav Generator
/**
* Helper Function
--------------------------------------------------------------------------*/
String.prototype.repeat = function(count) {
if (count < 1) return '';
var result = '', pattern = this.valueOf();
while (count > 0) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
return result;
};
/**
* Responsive Navigation
--------------------------------------------------------------------------*/
(function() {
// Recursively creates responsive nav
var addChildren = function($rnav, $children, depth) {
// $children is an object of li's
$children.each(function() {
var $li = $(this),
$a = $li.children("a"),
selected = ($li.hasClass("active")) ? "selected" : "";
$rnav.append(
$("<option "+selected+">")
.attr("value", $a.attr("href"))
.text("-- ".repeat(depth) + $a.text())
);
addChildren($rnav, $li.children("ul").children("li"), depth+1);
});
};
if (display_width < 480) {
$("[role=navigation]").each(function() {
var $nav = $(this),
$rnav = $("<select class=\"responsive-navigation\">")
.change(function() {
window.location = $(this).children(":selected").attr("value");
})
.appendTo($nav);
addChildren($rnav, $nav.children("ul").children("li"), 0);
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment