I’m looking for a solution to only display a div if there is space to do so.
On my blog’s post pages I display latest posts in the left sidebar, like so…
I want to show a different number of sidebar items dependent on how long the post is. Currently I have three divs displaying different numbers of items and run this script.
if ($("#contentheight").height()>960 && $("#contentheight").height()<1200) {
document.getElementById("threeposts").className += "hide";
}
else if ($("#contentheight").height()>1200 && $("#contentheight").height()<1880) {
document.getElementById("fiveposts").className += "hide";
}
else if ($("#contentheight").height()>1880) {
document.getElementById("sevenposts").className += "hide";
}
However, this is hardly convenient and for very short posts it shows no items at all.
Is there a workaround whereby I can, for example, code for 7 items, but only show as many as the parent div can take? I tried using overflow:hidden but then you end up with the end item chopped in half.
For example, if there is enough room for three full items, they would be shown but any after that would not.
You can create a hidden div or a div which is not inserted into the DOM with the desired width.
Then insert item by item until the height of this div exceeds the length of your post.
Now you know how many items will fit into the div.