Ralphonz Ralphonz - 2 months ago 14
jQuery Question

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!


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) {
        return false; // Abort loop

I put auto scrolling on the menu so you can actually see what is overflowed.