Hi all,
I am new to jquery and running a script on my homepage that determines the number of lines in a container (i.e. div). If the number of lines is over 3 or 4 lines (depending on whether div class is "threeline" or "fourline"), it will truncate it and add an ellipsis. However, this script is taking forever to execute so I'm wondering why or how it can be optimized. I've tried to wrap my head around javascript/jquery, but it truly is a foreign language to me!
Can someone please take a look at this script and let me know how I can edit it to make it faster? Is it unnecessarily checking all elements on the page?
Here is how it is called on my php page:
<div class="bubble left">
<div class="rounded">
<blockquote class="ellipsis fourline">
<h3><a href="http://www.xyz.com">This is the title</a></h3>
<p>This is the body of the quote; if the body plus title is more than fourlines, then the text will be truncated and an ellipsis will be added</p>
</blockquote>
</div>
<cite class="rounded">March 18, 2010</cite>
</div>
<script type="text/javascript" src="/scripts/js/jquery.ellipsis.js"></script>
<script type="text/javascript"> $(".ellipsis").ellipsis(); </script>
And this is the jquery.ellipsis.js file:
(function($) {
$.fn.ellipsis = function()
{
return this.each(function()
{
var el = $(this);
if(el.css("overflow") == "hidden" && el.hasClass('fourline'))
{
var text = el.html();
var fourline = el.hasClass('fourline');
var t = $(this.cloneNode(true))
.hide()
.css('position', 'absolute')
.css('overflow', 'visible')
.width(fourline ? el.width() : 'auto')
.height(fourline ? 'auto' : el.height())
;
el.after(t);
function height() { return t.height() > el.height(); };
function width() { return t.width() > el.width(); };
var func = fourline ? height : width;
while (text.length > 0 && func())
{
text = text.substr(0, text.length - 1);
t.html(text + "…");
}
el.html(t.html());
t.remove();
} else if (el.css("overflow") == "hidden" && el.hasClass('threeline'))
{
var text = el.html();
var threeline = el.hasClass('threeline');
var t = $(this.cloneNode(true))
.hide()
.css('position', 'absolute')
.css('overflow', 'visible')
.width(threeline ? el.width() : 'auto')
.height(threeline ? 'auto' : el.height())
;
el.after(t);
function height() { return t.height() > el.height(); };
function width() { return t.width() > el.width(); };
var func = threeline ? height : width;
while (text.length > 0 && func())
{
text = text.substr(0, text.length - 1);
t.html(text + "…");
}
el.html(t.html());
t.remove();
}
});
};
})(jQuery);
Thanks in advance, I love this site!