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

75 lines
1.9 KiB
JavaScript
Raw Normal View History

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