Skip to content

Instantly share code, notes, and snippets.

@cladley
Created May 20, 2016 13:25
Show Gist options
  • Save cladley/c47fb222fb9d3c126fdacbeff2973d2e to your computer and use it in GitHub Desktop.
Save cladley/c47fb222fb9d3c126fdacbeff2973d2e to your computer and use it in GitHub Desktop.
var attach = require('attach.js');
var utils = require('./helpers/utils');
var constants = require('./helpers/const');
/**
* Create a new accordion object
* @param {HTMLElement} el
*/
function Accordion(el) {
this.$element = $(el);
this.options = $.extend({}, this.options, this.$element.data('accordion-options') || {});
this.$toggle = this.$element.find(this.options.toggle).first();
this.$content = this.$element.find(this.options.content).first();
this.isAnimating = false;
this.attach();
}
Accordion.prototype = {
constructor: Accordion,
options: {
toggle: '.accordion-toggle', // Object that causes accordion to be triggered
content: '.accordion-content', // Content that is shown or hidden
isActive: 'is-active',
mobileOnly: false // Should only be active when we are at a mobile viewport
},
/**
* Attach any dom events
*/
attach: function () {
this.$toggle.on('click', this.toggle.bind(this));
var resizeFunc = utils.debounce(this.onresize.bind(this), 50);
$(window).on('resize', resizeFunc);
},
/**
* Get the current window width and perform check to see if we
* remove or display the accordion
* @param {Object} e DOM event
*/
onresize: function (e) {
var currentWidth = e.target.innerWidth;
if (this.options.mobileOnly && currentWidth > constants.MOBILE_WIDTH) {
this.$content.attr('style', '');
this.$element.removeClass(this.options.isActive);
}
},
/**
* Check to see if we are below a certain width
* @returns {bool}
*/
isMobile: function(){
return window.innerWidth <= constants.MOBILE_WIDTH;
},
/**
* Show or hide the accordion content
* @param {Object} e Dom event
*/
toggle: function (e) {
e.preventDefault();
if(!this.isAnimating){
if (this.options.mobileOnly && this.isMobile()) {
this.toggleContent();
} else if (!this.options.mobileOnly) {
this.toggleContent();
}
}
},
toggleContent: function () {
this.isAnimating = true;
this.$content.slideToggle(400, function () {
this.$element.toggleClass(this.options.isActive);
this.$toggle.toggleClass(this.options.isActive);
this.isAnimating = false;
}.bind(this));
}
};
attach.add('App.Accordion', function (el) {
el['App.Accordion'] = el['App.Accordion'] || new Accordion(el);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment