Skip to content

Instantly share code, notes, and snippets.

@nicinabox
Created June 28, 2012 15:34
Show Gist options
  • Save nicinabox/3012041 to your computer and use it in GitHub Desktop.
Save nicinabox/3012041 to your computer and use it in GitHub Desktop.
Elastic navigation for responsive designs

Elastic navigation

Demo

Accepts 1 parameter:

  • An integer that is the width to stop being elastic

app.js

$('#main-nav').elasticNav(767);

app.html

<nav>
  <a href="">Item 1</a>
  <a href="">Item 2</a>
  <a href="">Item 3</a>
  <a href="">Item 4</a>
  <a href="">Item 5</a>
</nav>
$.fn.elasticNav = function(stop_width) {
var $this = this,
$window = $window || $(window),
stop_width = stop_width || 0;
var usedWidth = function() {
var children_width = 0,
margins = 0;
$this.children().each(function(i) {
if ($(this).is(':visible')) {
children_width += $(this).width();
margins += parseInt($(this).css('margin-left'), 10);
margins += parseInt($(this).css('margin-right'), 10);
}
});
children_width += margins;
if (children_width < 0) {
children_width = 0;
}
return children_width;
};
var setChildWidths = function(children_width) {
$this.children().each(function(i) {
var w, width;
if ($(this).data('width') && $window.width() >= stop_width) {
return false;
}
if ($window.width() <= stop_width) {
children_width = '';
}
if (children_width) {
w = $(this).width();
width = (w / children_width) * 100 + '%';
} else {
width = children_width;
}
$(this).css({
width: width
});
if (children_width) {
$(this).data('width', width);
} else {
$(this).data('width', null);
}
});
};
$this.each(function(e) {
var children_width = usedWidth();
setChildWidths(children_width);
$window.on('resize', function(e) {
setTimeout(function() {
children_width = usedWidth();
setChildWidths(children_width);
}, 500);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment