Why does an overcrowded menu work poorly when there are 0 items in the visible original ul?

This is what the problem looks like: enter image description here

For now, it should look like this:

enter image description here

Here is the function used to create the popup menu:

function updateMenu(){
    var lastItemIndex = Number.POSITIVE_INFINITY;
    var lastItemText = "";
    var maxWidth = 0;
    var overflowCount=0;
    var navHeight = $('.nav').height();
    $('.nav li').each(function(i,e){
            if(i<lastItemIndex) lastItemIndex=i-1;
            if($(e).width()>maxWidth) maxWidth = $(e).width();
    maxWidth = Math.max(maxWidth,$('.nav li:eq('+(lastItemIndex)+')').width());
    var moreHeight = (overflowCount+2)*navHeight;
        $('<ul id="moreMenu"/>').appendTo('body').width(maxWidth+16).height(navHeight);
        $('#moreMenu').offset($('.nav li:eq('+(lastItemIndex)+')').offset());
        $('.nav li:gt('+(lastItemIndex-1)+')').each(function(i,e){


And here is a jafiddle life demo of this error (I'm using chrome for testing).

I wonder what is wrong with my updateMenu function, why, when all menu items are supposed to appear in the popup menu, nothing is actually displayed (and the html does not fit into the popup menu object)?

The fire fox update also doesn't show me any items: enter image description here


source to share

1 answer

One problem is that the selector you form with "lastItemIndex" when this zero is invalid:

$('.nav li:gt(' + (lastItemIndex - 1) + ')') ...


When it is zero it will look like .nav li:gt(-1)

and it is not valid (or at least it doesn't work). If you change it to:

$('.nav li:gt(' + Math.max(0, lastItemIndex - 1) + ')')


then the items <li>

are transferred to the "Advanced" field.

As a separate note, it is probably not a good idea to update the "resize" handler. Browsers fire this event very quickly, and doing all this DOM work will result in slow behavior. Instead, you can have the "resize" handler start the timer for 50 or 100 milliseconds, overriding any previous timer when it does. When the user slows down the resize, the timer event fires and you can do DOM work there.

Here is a jsfiddle updated with a selector fix (no change in event handling).



All Articles