Created
October 10, 2012 00:29
-
-
Save Schonhoffer/3862409 to your computer and use it in GitHub Desktop.
collapsible_comments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
'use strict'; | |
var fullHtmlDataKey = 'TruncateTextFullHtml', | |
truncate = function ($el, animate) { | |
$el.find('a.collapse').remove(); | |
var fullHtml = $el.html(), | |
fullHtmlLength = fullHtml.length, | |
newLength = fullHtmlLength > 128 ? 128 : fullHtmlLength, | |
newHtml = fullHtml.substr(0, newLength) + '...', | |
$hiddenClone = createHiddenClone($el); | |
$hiddenClone.data(fullHtmlDataKey, fullHtml); | |
$hiddenClone.html(newHtml); | |
$hiddenClone.append('<a href="#" class="expand">[Expand]</a>'); | |
$el.after($hiddenClone); | |
slideReplace($hiddenClone, $el, animate ? 400 : 1); | |
}, | |
expand = function ($el) { | |
var fullHtml = $el.data(fullHtmlDataKey), | |
$hiddenClone = createHiddenClone($el); | |
$hiddenClone.html(fullHtml); | |
$hiddenClone.append('<a href="#" class="collapse">[Collapse]</a>'); | |
$el.after($hiddenClone); | |
slideReplace($hiddenClone, $el); | |
}, | |
slideReplace = function ($inEl, $outEl, duration) { | |
duration = duration || 400; | |
$inEl.slideDown(duration); | |
$outEl.slideUp(duration, function () { $outEl.remove(); }); | |
}, | |
createHiddenClone = function ($el) { | |
return $el.clone(true).css('display', 'none'); | |
}; | |
$.fn.truncateText = function (commentSelector) { | |
this.find(commentSelector).each(function (i, el) { | |
var $el = $(el); | |
if ($el.html().trim().length > 128) { | |
truncate($el); | |
} | |
}); | |
this.on('click.truncateText', 'a.expand', function (e) { | |
expand($(e.currentTarget).closest(commentSelector)); | |
e.preventDefault(); | |
}); | |
this.on('click.truncateText', 'a.collapse', function (e) { | |
truncate($(e.currentTarget).closest(commentSelector), true); | |
e.preventDefault(); | |
}); | |
return this; | |
}; | |
} (jQuery)); | |
$(document).ready(function () { | |
$('.comments').truncateText('.comment'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment