/** * jquery.toggleItems * @version $Id$ * @uses jQuery */ (function ($) { var _pluginName = 'toggleItems'; var _defaultOptions = { max: 5, showLabel: 'Show More', hideLabel: 'Show Less', containerClass: 'toggleItemsContainer', linkClass: 'toggleItemsLink', linkWrapperClass: 'toggleItemsLinkWrapper' }; var _helpers = { /** * Returns existing container for hidden items if exists or creates new otherwise * @this {jQuery} Plugin instance * @param {jQuery} wrapper Items wrapper * @return {jQuery} */ initContainer: function (wrapper) { var container = wrapper.children(this.options.containerClass); if (0 === container.size()) { container = $(document.createElement('div')).addClass(this.options.containerClass).appendTo(wrapper); } container.css({display: 'none', margin: 0, padding: 0}); return container; }, /** * Method used to create wrapper for hidden items * @this {jQuery} Plugin instance */ wrapItems: function () { }, /** * @this {jQuery} Plugin instance * @param {jQuery} wrapper Items wrapper * @return {jQuery} */ initToggleLink: function (wrapper, hiddenContainer) { var that = this, link = wrapper.children(this.options.linkClass), linkWrapper; if (0 === link.size()) { linkWrapper = $(document.createElement('div')) .addClass(this.options.linkWrapperClass); link = $(document.createElement('a')) .attr('href', '#') .addClass(this.options.linkClass) .text(this.options.showLabel) .appendTo(linkWrapper); linkWrapper.appendTo(wrapper); } link.bind('click.' + _pluginName, function (e) { _helpers.onLinkClick.call(that, e, hiddenContainer); }); return link; }, /** * @this {jQuery} Plugin instance * @param {Event} e */ onLinkClick: function (e, hiddenContainer) { var that = this, target = $(e.currentTarget); e.preventDefault(); hiddenContainer.slideToggle(function () { target.text(hiddenContainer.is(':visible') ? that.options.hideLabel : that.options.showLabel); }); } }; $.fn.toggleItems = function (options) { var that = this; options = this.options = $.extend({}, _defaultOptions, options || {}); return this.each(function () { var $this = $(this), children2Hide = $this.children(':visible:gt(' + (options.max - 1) +')'), hiddenContainer; if (children2Hide.size()) { hiddenContainer = _helpers.initContainer.call(that, $this); _helpers.initToggleLink.call(that, $this, hiddenContainer); children2Hide.detach().appendTo(hiddenContainer); } }); }; })(jQuery);