Skip to content

Instantly share code, notes, and snippets.

@davetayls
Created October 10, 2012 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davetayls/3866822 to your computer and use it in GitHub Desktop.
Save davetayls/3866822 to your computer and use it in GitHub Desktop.
simple jquery collapsible container plugin
/**
jQuery.collapseContainer v0.1
Dave Taylor http://the-taylors.org
@license The MIT License (MIT)
*/
/*global define,require */
(function($){
'use strict';
var uniqueId = 0,
OPEN_CLASS = 'collapseContainer-open'
;
var CollapseContainer = function(el, options){
if (el || options){ this.init(el, options); }
};
CollapseContainer.prototype = {
defaults: {
scrollTo: true
},
init: function(el, options){
var self = this;
this.$el = $(el);
this.containerId = el.id = el.id || 'collapseContainer' + (uniqueId++);
this.settings = $.extend({}, this.defaults, options);
$.collapseContainer.containers.push(this); // add to global list
this.$el.hide(); // hide this container initially
this.$el.data('collapseContainer', this);
return this;
},
visible: function(){
return this.$el.hasClass(OPEN_CLASS);
},
expand: function(){
this.$el
.addClass(OPEN_CLASS)
.show();
},
collapse: function(){
this.$el
.removeClass(OPEN_CLASS)
.hide();
},
toggle: function(){
if (this.visible()){
this.collapse();
} else {
this.expand();
}
},
scrollTo: function(){
$('html,body').animate({ scrollTop: this.$el.offset().top }, 1000, 'swing');
}
};
$.collapseContainer = {
containers: []
};
$.fn.collapseContainer = function(options) {
return this.each(function(){
var collapseContainer = new CollapseContainer(this, options);
});
};
// listener to toggle container visibility
$(document).on('click', 'a[href^="#"]', function(e){
var linkId = $(this).attr('href');
$($.collapseContainer.containers).each(function(){
if ('#'+this.containerId === linkId){
this.toggle();
if (this.settings.scrollTo){
this.scrollTo();
}
e.preventDefault();
}
});
});
}(this.jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment