Skip to content

Instantly share code, notes, and snippets.

@ShaunSpringer
Created February 26, 2012 06:13
Show Gist options
  • Save ShaunSpringer/1914196 to your computer and use it in GitHub Desktop.
Save ShaunSpringer/1914196 to your computer and use it in GitHub Desktop.
jQuery Toggle List
/*
* jQuery Toggle List v1.0.0
*
* Date: 2012-02-26
* Requires: jQuery v1.7+
*
* Copyright 2012, Shaun Springer
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*
* USAGE EXAMPLE: http://jsfiddle.net/Springerlax11/7c2cV/
*/
(function($) {
$.toggleList = {
version: '1.0.0',
defaults: {
show: {
html: '<div class="list-more"><a href="#">more...</a></div>',
classname: 'list-more'
},
hide: {
html: '<div class="list-less"><a href="#">less...</a></div>',
classname: 'list-less'
},
visibleItems: '3',
onCollapse: null,
onExpand: null
}
};
$.fn.toggleList = function(options) {
var opts = $.extend({}, $.toggleList.defaults, options);
//lets make overflow hidden
this.css({
"overflow": "hidden"
});
//trigger the first toggle
toggle(this, true, opts);
};
function toggle(target, show, opts) {
var list = $(target).children();
var len = list.length - 1;
var limit = show ? opts.visibleItems - 1 : len;
//if our limit is greater than our list length, exit
if (len < opts.visibleItems) {
return;
}
//if we have a limit of 0, noting to do here
if (limit === 0) {
return;
}
var $toggle = $(opts[!show ? "hide" : "show"].html);
$toggle.find('a').click(function() {
toggle(target, !show, opts);
});
//get our item from the array
var $item = $(list[limit]);
//remove the old show/hide item
target.find('.' + opts[show ? "hide" : "show"].classname).remove();
//insert the new show/hide item
target.append($toggle);
//show or hide list items based on transition direction
var i;
if (show) {
for (i = limit + 1; i <= len; i++) {
$(list[i]).slideToggle(250, "swing");
}
opts.onExpand.apply();
}
else {
for (i = opts.visibleItems; i <= len; i++) {
$(list[i]).slideToggle(250, "swing");
}
opts.onCollapse.apply();
}
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment