// custom method to fit text into its container
BISN.truncateTextToFit = function(container) {
// 18 & 24 cludge to allow for line-height could be cleaner
var x = $(container).width() - 18;
var y = $(container).height() - 24;
var p = '';
var c = 0;
var currentX1;
var currentX2;
var currentY1;
var currentY2;
// get the original text we got from the server
// the page may have just changed size
var parag = $.trim($(container).attr('data'));
var words = parag.split(' ');
c = words.length;
var saver = '';
// iterate through the text and test
// each word to see if it lay beyond
// the bounds of enclosing rectangle
for (var i = 0; i < c; i++)
{
p = '';
// load the text as it is now
$(container).html(parag);
// incrementally wrap each word with a span
for (var w = 0; w < c; w++)
{
if (w === i)
{
// save the text as it is right now
saver = p + "...";
p += '<span class="wPos">' + words[w] + '</span> ';
}
else
{
p += words[w] + ' ';
}
}
// put the text back with one word wrapped
$(container).html(p);
// see if the position of that word is passed our boundary
if ($('.wPos').size() > 0) {
currentX1 = $('.wPos').position().left;
currentX2 = currentX1 + $('.wPos').width();
currentY1 = $('.wPos').position().top;
currentY2 = currentY1 + $('.wPos').height();
// if this is the end, set the text, stop looking and leave
if ((currentX2 > x) && (currentY2 > y))
{
$(container).html(saver);
return;
}
}
}
};
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.