Skip to content

Instantly share code, notes, and snippets.

@superp
Created April 16, 2014 06:41
Show Gist options
  • Save superp/10818213 to your computer and use it in GitHub Desktop.
Save superp/10818213 to your computer and use it in GitHub Desktop.
jQuery Switcher
var $, Switcher;
$ = jQuery;
$.fn.extend({
switcher: function(options) {
return $(this).each(function(input_field) {
var switcher;
switcher = $(this).data("switcher");
if (switcher == null) {
switcher = new Switcher(this, options);
}
return switcher;
});
}
});
Switcher = (function() {
function Switcher(dom_element, options) {
var defaults;
this.dom_element = dom_element;
if (options == null) {
options = {};
}
defaults = {
container: ".header_switch .switch",
wrapper: ".switch .state-wrapper",
navigation: ".header_switch b",
snap_tolerance: 35,
default_state: "center",
left: 11,
right: 166,
center: 177,
start: 89,
callback: null
};
this.options = $.extend(defaults, options);
this._setup();
this._events();
}
Switcher.prototype._setup = function() {
this.switcher = $(this.dom_element);
this.current_state = this.options.default_state;
this.switcher.draggable({
axis: "x",
snap: this.options.wrapper,
snapTolerance: this.options.snap_tolerance,
containment: "parent",
stop: (function(_this) {
return function(event, ui) {
return _this._changeState(ui.position.left);
};
})(this)
});
return this.switcher.data("switcher", this);
};
Switcher.prototype._events = function() {
var self;
self = this;
$(this.options.container).click((function(_this) {
return function(event) {
if (event.offsetX < _this.options.center) {
return _this.move(_this.options.left);
} else {
return _this.move(_this.options.right);
}
};
})(this));
return $(this.options.navigation).click(function() {
return self.move(self.options[$(this).attr('rel')]);
});
};
Switcher.prototype.move = function(position) {
this._changeState(position);
return this.switcher.animate({
left: position + 'px'
}, 500);
};
Switcher.prototype._changeState = function(position) {
if (position === this.options.left) {
this.current_state = "brand";
} else if (position === this.options.right) {
this.current_state = "writer";
} else {
this.current_state = "center";
this.switcher.css("left", this.options.start + "px");
}
if ($.isFunction(this.options.callback)) {
return this.options.callback.apply(this, [this]);
}
};
return Switcher;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment