﻿(function($) { $.fn.expander = function(options) { var opts = $.extend({}, $.fn.expander.defaults, options); var delayedCollapse; return this.each(function() { var $this = $(this); var o = $.meta ? $.extend({}, opts, $this.data()) : opts; var cleanedTag, startTags, endTags; cleanedTag = ''; var allText = $this.html(); var startText = allText.slice(0, o.slicePoint).replace(/(\w)$/, ''); startTags = startText.match(/<\w[^>]*>/g); if (startTags) { startText = allText.slice(0, o.slicePoint + startTags.join('').length).replace(/\w+$/, '') } if (startText.lastIndexOf('<') > startText.lastIndexOf('>')) { startText = startText.slice(0, startText.lastIndexOf('<')) } var endText = allText.slice(startText.length); if (!$('span.details', this).length) { if (endText.replace(/\s+$/, '').split(' ').length < o.widow) { return } if (endText.indexOf('</') > -1) { endTags = endText.match(/<(\/)?[^>]*>/g); for (var i = 0; i < endTags.length; i++) { if (endTags[i].indexOf('</') > -1) { var startTag, startTagExists = false; for (var j = 0; j < i; j++) { startTag = endTags[j].slice(0, endTags[j].indexOf(' ')).replace(/(\w)$/, '$1>'); if (startTag == rSlash(endTags[i])) { startTagExists = true } } if (!startTagExists) { startText = startText + endTags[i]; var matched = false; for (var s = startTags.length - 1; s >= 0; s--) { if (startTags[s].slice(0, startTags[s].indexOf(' ')).replace(/(\w)$/, '$1>') == rSlash(endTags[i]) && matched == false) { cleanedTag = cleanedTag ? startTags[s] + cleanedTag : startTags[s]; matched = true } } } } } endText = cleanedTag && cleanedTag + endText || endText } $this.html([startText, '<a href="#" class="read-more">', o.expandText, '</a>', '<span class="details">', endText, '</span>'].join('')) } $this.find('span.details').hide().end().find('a.read-more').click(function() { $(this).hide().next('span.details')[o.expandEffect](o.expandSpeed, function() { var $self = $(this); $self.css({ zoom: '' }); if (o.collapseTimer) { delayedCollapse = setTimeout(function() { reCollapse($self) }, o.collapseTimer) } }); return false }); if (o.userCollapse) { $this.find('span.details').append(' <a class="re-collapse" href="#">' + o.userCollapseText + '</a>').find('a.re-collapse').click(function() { clearTimeout(delayedCollapse); var $spanCollapse = $(this).parent(); reCollapse($spanCollapse); return false }) } }); function reCollapse(el) { el.hide().prev('a.read-more').show() } function rSlash(rString) { return rString.replace(/\//, '') } }; $.fn.expander.defaults = { slicePoint: 15, widow: 4, expandText: '[...]', collapseTimer: 0, expandEffect: 'fadeIn', expandSpeed: '', userCollapse: true, userCollapseText: '[«]'} })(jQuery);
