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){
    console.log($(e).position().top);
        if($(e).position().top>=navHeight){
            if(i<lastItemIndex) lastItemIndex=i-1;
            if($(e).width()>maxWidth) maxWidth = $(e).width();
            overflowCount++;
        }
    });
    maxWidth = Math.max(maxWidth,$('.nav li:eq('+(lastItemIndex)+')').width());
    var moreHeight = (overflowCount+2)*navHeight;
    $('#moreMenu').remove();
    if(overflowCount>0){
        $('<ul id="moreMenu"/>').appendTo('body').width(maxWidth+16).height(navHeight);
        $('#moreMenu').offset($('.nav li:eq('+(lastItemIndex)+')').offset());
        $('#moreMenu').append('<li>More...</li>');
        $('.nav li:gt('+(lastItemIndex-1)+')').each(function(i,e){
            $('#moreMenu').append('<li>'+$(e).html()+'</li>');
        });
        $('#moreMenu').hover(
            function(){$(this).height(moreHeight);},
            function(){$(this).height(navHeight);});
    }
}

      

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

+3


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).

+2


source







All Articles