Using the jQuery dotdotdot plugin, I would like to have both a More and Less button to show and hide entire content of a <div>
when there is a lot of text to display. The More button is working just fine, but I haven't yet figured out a way to return the <div>
to it's original display. Note that this is not just about how to use dotdotdot to expand a truncated string because it incorporates the Less button re-truncate a long string.
Here is my code:
$(function() {
$("div.ellipsis-text").dotdotdot({
after: 'a.more',
callback: dotdotdotCallback
});
$("div.ellipsis-text").find("a").click(function() {
if ($(this).text() == "More") {
var div = $(this).closest('div.ellipsis-text');
div.trigger('destroy').find('a.more').hide();
div.css('max-height', '');
$("a.less", div).show();
}
else {
$(this).text("More");
$(this).closest('div.ellipsis-text').css("max-height", "50px").dotdotdot({ after: "a", callback: dotdotdotCallback });
}
});
function dotdotdotCallback(isTruncated, originalContent) {
if (!isTruncated) {
$("a", this).remove();
}
}
});
It seems that the click
event handler for the <div>
's anchor tags is getting removed, I am never able to reach the event handler after the More button is clicked.
Solution found:
$(function() {
$("div.ellipsis-text").dotdotdot({
after: 'a.more',
callback: dotdotdotCallback
});
$("div.ellipsis-text").on('click','a',function() {
if ($(this).text() == "More") {
var div = $(this).closest('div.ellipsis-text');
div.trigger('destroy').find('a.more').hide();
div.css('max-height', '');
$("a.less", div).show();
}
else {
$(this).hide();
$(this).closest('div.ellipsis-text').css("max-height", "50px").dotdotdot({ after: "a.more", callback: dotdotdotCallback });
}
});
function dotdotdotCallback(isTruncated, originalContent) {
if (!isTruncated) {
$("a", this).remove();
}
}
});
Thanks, guys!