<div id="to-hide">I am some text and more text and so on and on I just keep going.</div>
<div>Visible</div>
<div id="visible"></div>
<div>Hidden</div>
<div id="hidden"></div>
$.fn.visibleText = function () {
// Get the currents
var currWidth = this.width();
var currHeight = this.height();
var htmlContent = this.html();
var lineHeight = parseFloat(this.css("lineHeight"), 10);
// Need to calculate the number of lines visible
// as currHeight < numLines * lineHeight, at times
// Eg: Try changing height to 4.4em and width to 110px
var numLines = Math.round(currHeight / lineHeight);
var actualHeight = (numLines * lineHeight);
// Clearing
this.html("");
this.height("initial");
// Push to HTML until hitting the terminating conditions
// currWordLength is required since wrapping of a word could push
// to the line
var vContent = "",
currWordLength = 0;
while (this.height() <= actualHeight) {
var currChar = htmlContent[vContent.length];
vContent += currChar;
this.html(vContent);
if (currChar === " ") {
currWordLength = 0;
}
currWordLength++;
if (htmlContent.length === vContent.length) {
currWordLength = 0;
break;
}
}
var visible = vContent.substring(0, vContent.length - currWordLength);
// Revert to originals
this.height(currHeight);
this.html(htmlContent);
return {
visible: visible,
hidden: htmlContent.substring(visible.length, htmlContent.length)
}
};
var x = $("#to-hide").visibleText();
$("#visible").html(x.visible);
$("#hidden").html(x.hidden);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.