I’m using this code in order to show just the first 500 chars (and cut only after a complete word) of a text, but it fails apparently when it finds some HTML code in the “500” threshold.
In that case, it just adds the “…” and then continues the text (and it displays the “See More” link as well).
Eg:
Lorem <strong>impsum dolor</strong> sit amet. Etcétera.
Let’s say it should cut the text between “impsum” and “dolor”. The result is:
Lorem <strong>impsum...<span class="hidden" style="display:none;">dolor</span></strong> sit amet. Etcétera. <a href="#">See More</a>
It should be:
Lorem <strong>impsum... <span class="hidden" style="display:none;">dolor</strong> sit amet. Etcétera</span><a href="#">See More</a>
or…
Lorem <strong>impsum dolor</strong>... <span class="hidden" style="display:none;">sit amet. Etcétera</span<a href="#">See More</a>
Any way would be ok, I just want to cut the text after that. Is there any way to fix this?
Code:
(function ($) {
$.fn.readmore = function (settings) {
$('.home_excerpt').removeClass('home_excerpt');
var opts = $.extend({}, $.fn.readmore.defaults, settings);
this.each(function () {
$(this).data("opts", opts);
if ($(this).html().length > opts.substr_len) {
abridge($(this));
linkage($(this));
}
});
function linkage(elem) {
elem.append(elem.data("opts").more_link);
$(".text_seemore").click( function () {
$(this).hide();
$(this).siblings("span:not(.hidden)").hide().siblings("span.hidden").show();
return false;
});
}
function abridge(elem) {
var opts = elem.data("opts");
var txt = elem.html();
var len = opts.substr_len;
var dots = "<span>" + opts.ellipses + "</span>";
var charAtLen = txt.substr(len, 1);
while (len < txt.length && !/\s/.test(charAtLen)) {
len++;
charAtLen = txt.substr(len, 1);
}
var shown = txt.substring(0, len) + dots;
var hidden = '<span class="hidden" style="display:none;">' + txt.substring(len, txt.length) + '</span>';
elem.html(shown + hidden);
}
return this;
};
$.fn.readmore.defaults = {
substr_len: 500,
ellipses: '…',
more_link: '<br /><a href="#" class="text_seemore">See More</a>'
};
})(jQuery);
I just found this jquery plugin that works perfect with HTML tags:
http://plugins.learningjquery.com/expander/index.html