Skip to content

Instantly share code, notes, and snippets.

@dervalp
Created September 20, 2012 06:27
Show Gist options
  • Select an option

  • Save dervalp/3754258 to your computer and use it in GitHub Desktop.

Select an option

Save dervalp/3754258 to your computer and use it in GitHub Desktop.
Writing javascript in a declarative way
!function($) {
"use strict"; // jshint ;_;
var customEl = '[data-toggle="sc-toggle"]'
, Toggle = function(el) {
var $el = $(element).on('click.customevent.data-api', this.toggle)
$('html').on('click.customevent.data-api', function() {
$el.parent().removeClass('open')
})
};
Toggle.prototype = {
constructor: Toggle,
toggle: function(e) {
var $this = $(this)
, $parent
, isActive;
if ($this.is('.disabled, :disabled')) return
$parent = getParent($this);
isActive = $parent.hasClass('open');
$parent.toggleClass('open');
if (isActive) {
$parent.fadeOut();
} else {
$parent.fadeIn();
}
return false;
}
};
function getParent($this) {
var selector = $this.attr('data-target')
, $parent;
if (!selector) {
selector = $this.attr('href');
selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, ''); //strip for ie7
}
$parent = $(selector);
$parent.length || ($parent = $this.parent());
return $parent;
}
/* custom PLUGIN DEFINITION
* ========================== */
$.fn.custom = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('sc-toggle');
if (!data) $this.data('sc-toggle', (data = new Toggle(this)));
if (typeof option == 'string') data[option].call($this);
})
}
$.fn.custom.Constructor = Toggle;
$(function() {
$('body').on('click.sc-toggle.data-api', customEl, Toggle.prototype.toggle);
});
}(window.jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment