So everything works perfectly, until an ajax call is made and the function is called to run on the newly updated text. I understand that it’s because it’s an .each() not .live(), but I’m not sure how to make the function work on the newly updated text from ajax.
The html & css:
.ellipsis {
white-space: nowrap;
overflow: hidden;
}
.ellipsis.multiline {
white-space: normal;
}
<div class="ellipsis" style="width: 100px; border: 1px solid black;">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>
<div class="ellipsis multiline" style="width: 100px; height: 40px; border: 1px solid black; margin-bottom: 100px">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>
<script type="text/javascript" src="/js/jquery.ellipsis.js"></script>
<script type="text/javascript">
$(".ellipsis").ellipsis();
</script>
jquery.ellipsis.js (The function is this ellipsis):
(function($) {
$.fn.ellipsis = function()
{
return this.each(function()
{
var el = $(this);
if(el.css("overflow") == "hidden")
{
var text = el.html();
var multiline = el.hasClass('multiline');
var t = $(this.cloneNode(true))
.hide()
.css('position', 'absolute')
.css('overflow', 'visible')
.width(multiline ? el.width() : 'auto')
.height(multiline ? 'auto' : el.height())
;
el.after(t);
function height() { return t.height() > el.height(); };
function width() { return t.width() > el.width(); };
var func = multiline ? height : width;
while (text.length > 0 && func())
{
text = text.substr(0, text.length - 1);
t.html(text + "...");
}
el.html(t.html());
t.remove();
}
});
};
})(jQuery);
This works fine on the text, however, once the text in the ellipsis div is updated to anything else from an ajax success callback, such as “Hi, I’m the new text in this div and should be trimmed”, it does not work. I want it to be applied to only the newly updated text from the success callback.
Here is what I’ve tried so far:
success: function(data) {
$(".ellipsis").text(data);
$(".ellipsis", data).ellipsis(); // not working
}
Here is the fiddle without the ajax http://jsfiddle.net/TF6Rb/625/
Any ideas?
Just do
$(".ellipsis").ellipsis();I should work fine.