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

I have a horizontal menu with overflow: a hidden application to it.

The menu is managed by CMS, so sometimes it does not overflow, but when it overflows, I want to find the last visible li element and insert the ul dropdown link with overflowed menu items. The problem I am facing is to select the last visible person (to insert the HTML in front of her) as the elements hidden by the overflow: the hidden ones still seem visible.

My code so far:

$(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 returns the total number of li elements, not just those visible to the person viewing the page!

+4
source share
2 answers

You cannot directly request elements that are overflowed because they are not hidden until the DOM (and there are no attribute changes to validate with jQuery).

You will need to check the positions instead of 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-scroll in the menu so you can see what is full.

+6
source

I just had to come up with a solution for this, so I decided that I would share it, and I hope this helps someone:

 function getVisible($elements, $container) { return $elements.filter(function (i, e) { var $e = $(e); return ($e.offset().left >= $container.offset().left) && ($e.offset().left + $e.width() <= $container.offset().left + $container.width()); }); } 

* Edit - this is only for checking the visible elements horizontally. For vertical, you need to add tests against offset().top vs. $container.height() etc.

+2
source

Source: https://habr.com/ru/post/1502057/


All Articles