hacks-guide-minimal-mistake.../assets/js/plugins/jquery.greedy-navigation.js

69 lines
1.7 KiB
JavaScript
Raw Normal View History

/*
2017-02-14 04:14:10 +01:00
GreedyNav.js - https://github.com/lukejacksonn/GreedyNav
Licensed under the MIT license - http://opensource.org/licenses/MIT
Copyright (c) 2015 Luke Jackson
*/
$(document).ready(function() {
var $btn = $("nav.greedy-nav .greedy-nav__toggle");
var $vlinks = $("nav.greedy-nav .visible-links");
var $hlinks = $("nav.greedy-nav .hidden-links");
2017-02-14 04:14:10 +01:00
var numOfItems = 0;
var totalSpace = 0;
var breakWidths = [];
2017-02-14 04:14:10 +01:00
// Get initial state
$vlinks.children().outerWidth(function(i, w) {
totalSpace += w;
numOfItems += 1;
breakWidths.push(totalSpace);
});
2020-03-11 00:00:43 +01:00
var availableSpace, numOfVisibleItems, requiredSpace;
2017-02-14 04:14:10 +01:00
function check() {
// Get instant state
availableSpace = $vlinks.width() - $btn.width();
2017-02-14 04:14:10 +01:00
numOfVisibleItems = $vlinks.children().length;
requiredSpace = breakWidths[numOfVisibleItems - 1];
2017-02-14 04:14:10 +01:00
// There is not enough space
if (requiredSpace > availableSpace) {
$vlinks
.children()
.last()
.prependTo($hlinks);
2017-02-14 04:14:10 +01:00
numOfVisibleItems -= 1;
check();
// There is more than enough space
} else if (availableSpace > breakWidths[numOfVisibleItems]) {
$hlinks
.children()
.first()
.appendTo($vlinks);
2017-02-14 04:14:10 +01:00
numOfVisibleItems += 1;
check();
}
2017-02-14 04:14:10 +01:00
// Update the button accordingly
$btn.attr("count", numOfItems - numOfVisibleItems);
if (numOfVisibleItems === numOfItems) {
$btn.addClass("hidden");
} else {
$btn.removeClass("hidden");
}
}
2017-02-14 04:14:10 +01:00
// Window listeners
$(window).resize(function() {
check();
});
$btn.on("click", function() {
$hlinks.toggleClass("hidden");
$(this).toggleClass("close");
2017-02-14 04:14:10 +01:00
});
2017-02-14 04:14:10 +01:00
check();
});