Skip to content

Instantly share code, notes, and snippets.

@dfrnswrth
Created September 4, 2013 00:15
Show Gist options
  • Save dfrnswrth/6431294 to your computer and use it in GitHub Desktop.
Save dfrnswrth/6431294 to your computer and use it in GitHub Desktop.
Breakpoint triggers in jQuery
/**
* Breakpoints
*/
/*global jQuery define*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(jQuery);
}
}(function ($) {
'use strict';
var Breakpoints = function(element, breakpoints){
this.$element = element;
this.$breakpoints = breakpoints;
this.$numberOfBreakpoints = this.$breakpoints.length;
this.$element.on("resize", $.proxy(this.doResize, this));
};
Breakpoints.prototype = {
$previous: null,
doResize: function() {
this.$width = this.$element.outerWidth();
if (!this.$previous) this.$previous = this.$width;
for (var i = 0; i < this.$numberOfBreakpoints; i++) {
var point = this.$breakpoints[i];
if (this.$width <= point && this.$previous > point ||
this.$width > point && this.$previous < point) {
this.triggerEnter(point);
}
}
this.$previous = this.$width;
},
triggerEnter: function(breakpoint) {
this.$direction = (this.$width > this.$previous) ? "expand" : "contract";
this.$element.trigger("breakpoint", {direction: this.$direction, size: breakpoint});
}
};
$.fn.breakpoints = function(breakpoints) {
return this.each(function(){
var $this = $(this),
data = $this.data("breakpoints");
if (!data) {
$this.data("breakpoints", (data = new Breakpoints($this, breakpoints)));
}
});
};
}));
/**
* Breakpoints
*/(function(e){typeof define=="function"&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){"use strict";var t=function(t,n){this.$element=t,this.$breakpoints=n,this.$numberOfBreakpoints=this.$breakpoints.length,this.$element.on("resize",e.proxy(this.doResize,this))};t.prototype={$previous:null,doResize:function(){this.$width=this.$element.outerWidth(),this.$previous||(this.$previous=this.$width);for(var e=0;e<this.$numberOfBreakpoints;e++){var t=this.$breakpoints[e];(this.$width<=t&&this.$previous>t||this.$width>t&&this.$previous<t)&&this.triggerEnter(t)}this.$previous=this.$width},triggerEnter:function(e){this.$direction=this.$width>this.$previous?"expand":"contract",this.$element.trigger("breakpoint",{direction:this.$direction,size:e})}},e.fn.breakpoints=function(n){return this.each(function(){var r=e(this),i=r.data("breakpoints");i||r.data("breakpoints",i=new t(r,n))})}});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment