Click or Tap to Reveal Hidden Overflow Text
When text must stay on one line, but there is not enough room for it, here's a solution.
The text that doesn't fit is the overflow. The overflow is hidden.
The hidden overflow is revealed with a click or tap. A second click or tap hides it again. An elipsis at the end of the visible text signals users that the overflow exists and is hidden.
Here's an example:
And here's the code for how to do it. (Notes follow.)
<div style=" white-space:nowrap; text-overflow:ellipsis; overflow:hidden;" onclick="RevealHiddenOverflow(this)"> Text that doesn't fit is hidden. Click here to reveal the text of the entire line. </div> <script type="text/javascript"> function RevealHiddenOverflow(d) { if( d.style.overflow == "hidden" ) { d.style.overflow = "visible"; } else { d.style.overflow = "hidden"; } } </script>
Notes:
The source code has two parts, the div with the text and the JavaScript to handle the overflow visibility.
The Div —
The inline CSS is what tells the browser to:
- Keep all text on one line (white-space:nowrap;).
- Hide any text that won't fit (overflow:hidden;).
- Print an elipsis at the end of the visible text if any is hidden (text-overflow:ellipsis;).
The overflow:hidden; rule needs to remain as inline style. Otherwise, it will take a click or tap to make the style accessible to the JavaScript and a second click or tap to reveal the hidden overflowed text.
The rest of the inline style may be moved to a style sheet. Additional CSS may be added for the div.
The div tag also contains onclick="RevealHiddenOverflow(this)", which calls the JavaScript when the div is clicked or tapped on.
The JavaScript —
The JavaScript can be anywhere on the page, even imported, if so desired. It's copy and paste code. Nothing needs to be customized.
Implementation:
Copy and paste the above example code into a test page to try it with your own text. To constrain the width, the example code can be put into another div with a maximum width specified.
When satisfied with the content and its behavior, the code on your test page is ready to paste into live web pages.
(This article first appeared in Possibilities ezine.)
Will Bontrager