More Less Overflow: Expand and Contract a Div

Here’s a simple jQuery project I packaged up to provide a more/less button to expand and contract a div with lots of text.  Yet another simple concept, but implemented very nicely and easy to reuse.


Github:  http://github.com/justinmc/More-Less-Overflow

Live Demo:  http://www.justinmccandless.com/demos/More-Less-Overflow/index.html


Go ahead and check out the demo so you know what we’re talking about.  There you go, a simple expanding and contracting div to view more content when necessary.  It has a few nice features besides just changing the height of a div though, so I’ll go over them here.


Use a more/less button only when necessary

The initial height of the div is detected and recorded, as well as the initial height of the inner element with the content.  If the inner stuff winds up being taller than its container, then it is shortened and a button is added.  Otherwise, the div will look just like normal.  If you have dynamic content going into this div, don’t worry about including it only when the content is long, it will only take action if it’s needed.


Shorten to the nearest word and append an ellipsis

The div isn’t just shortened to block the inner content with overflow: hidden;.  The text is actually removed from the element until it is short enough to add an ellipsis to the nearest word without overflowing.  This gives the best possible look for the user while still being conveniently automatic.


Use as many as you need on a page in different configurations

Use multiple on a page, some which are short and not needed, some which are very long, and they will all work nicely together without collisions.  You can also set the mlOverflow_more and mlOverflow_less data attributes and use different words for “more” and “less” on each.



That’s basically all there is to it.  If you need help setting up, check the readme for usage.  And take a look at the simple code in the demo to see an example.