March 16, 2012

Hide <li> element when not fully visible

Question by JeroenVdb

Basic: I have an unordered list with many listitems (containing a picture and title). Not knowing how long the title will be I don’t know the hight of each listitem. To the left of this list is a big picture with title that “sets” the hight of my list (depending of the height en length of the title).

What I try to do: When the last listitem of my list can’t be fully displayed, hide the whole listitem.

Examples: http://d.pr/eAlK & http://d.pr/8MVO

In the second example the 4th article is hidden because it wouldn’t be fully visible.

Is this possible? I prefer I clean way that works crossbrowser if possible…

Answer by Starx

Basically the idea is to calculate all the height of child elements together and compare with maximum allowed height.

Using jQuery

var neededHeight = $("#lhscontainer").outerHeight(); //you can also use static value 
var totalChildHeight = 0;
$("ul").children("li").each(function() {
    totalChildHeight+= $(this).outerHeight(); //add up to the total height 
    if(totalChildHeight> neededHeight) {  //compare if the height limit was exceeded
       $(this).hide(); // if it did, hide the current element
       $(this).nextAll().hide(); //hide all other list also
       return false; // break the loop to stop the further iteration
    }
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!