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

74 lines
1.9 KiB
JavaScript
Raw Normal View History

/*
2020-06-06 16:30:54 +02:00
GreedyNav.js - http://lukejacksonn.com/actuate
2017-02-14 04:14:10 +01:00
Licensed under the MIT license - http://opensource.org/licenses/MIT
Copyright (c) 2015 Luke Jackson
*/
2020-06-06 16:30:54 +02:00
$(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;
2020-06-06 16:30:54 +02:00
var closingTime = 1000;
2017-02-14 04:14:10 +01:00
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-06-06 16:30:54 +02:00
var availableSpace, numOfVisibleItems, requiredSpace, timer;
2017-02-14 04:14:10 +01:00
function check() {
2020-06-06 16:30:54 +02:00
2017-02-14 04:14:10 +01:00
// Get instant state
2020-06-06 16:30:54 +02:00
availableSpace = $vlinks.width() - 10;
2017-02-14 04:14:10 +01:00
numOfVisibleItems = $vlinks.children().length;
requiredSpace = breakWidths[numOfVisibleItems - 1];
2020-06-06 16:30:54 +02:00
// There is not enought space
2017-02-14 04:14:10 +01:00
if (requiredSpace > availableSpace) {
2020-06-06 16:30:54 +02:00
$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]) {
2020-06-06 16:30:54 +02:00
$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) {
2020-06-06 16:30:54 +02:00
$btn.addClass('hidden');
} else $btn.removeClass('hidden');
}
2017-02-14 04:14:10 +01:00
// Window listeners
$(window).resize(function() {
check();
});
2020-06-06 16:30:54 +02:00
$btn.on('click', function() {
$hlinks.toggleClass('hidden');
clearTimeout(timer);
2017-02-14 04:14:10 +01:00
});
2020-06-06 16:30:54 +02: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-14 04:14:10 +01:00
check();
2020-06-06 16:30:54 +02:00
});