Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the last visible li element within overflow:hidden element (jquery)

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!

like image 746
Ralphonz Avatar asked Feb 16 '23 07:02

Ralphonz


1 Answers

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.

JSFiddle here: http://jsfiddle.net/TrueBlueAussie/WFGJ4/

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.

like image 176
Gone Coding Avatar answered May 02 '23 00:05

Gone Coding