I have a horizontal menu with overflow:hidden applied to it.
The menu is CMS managed so sometimes it will not overflow, however when it does overflow I want to find the last visible li element and insert a drop down ul with the overflowing menu items in it. The problem i'm having is selecting the last li that is visible (in order to insert HTML before it) as elements hidden by overflow:hidden still seem to count as visible.
My code so far is:
$(window).load( function () {
var totalWidth = 0;
var menu = $('.nav .menu ul');
var menuWidth = menu.innerWidth();
menu.find('li').each(function() {
totalWidth += $(this).innerWidth() + 30; // add margin
});
if (totalWidth > menuWidth) {
var num_li = $('.nav .menu ul > li:visible').length;
$('.nav .menu ul li:nth-child('+num_li+')').append("<li><a>More</a></li>");
}
});
The variable num_li is returning the full number of li elements rather than just the ones visible to the person looking at the page!
You can't directly query for elements that are overflowing as they are not hidden as far as the DOM is concerned (and there are no attribute changes to check for with JQuery).
You will need to check positions instead against the width/height of the menu.
menu.find('li').each(function () {
totalWidth += $(this).outerWidth();
if (totalWidth > menuWidth) {
$(this).before("<li><a>More</a></li>");
return false; // Abort loop
}
});
I put auto scrolling on the menu so you can actually see what is overflowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With