Created
October 10, 2012 16:49
-
-
Save davetayls/3866822 to your computer and use it in GitHub Desktop.
simple jquery collapsible container plugin
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
/** | |
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