Skip to content

Instantly share code, notes, and snippets.

@robertcasanova
Created November 21, 2013 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertcasanova/7578003 to your computer and use it in GitHub Desktop.
Save robertcasanova/7578003 to your computer and use it in GitHub Desktop.
Image Breakpointer
(function($,window, document, undefined){
var defaults = {
resizing: true
};
var BreakpointManager = function(element, options) {
this.el = element;
this.$el = $(element);
this.options = $.extend({}, defaults,options);
this.breakpoints = {};
this._defaults = defaults;
this.init();
};
BreakpointManager.prototype = {
init: function() {
var micro_data = this.$el.data(),
src = "",
self = this,
win_width = $(window).width(),
win_height = $(window).height();
if($.isEmptyObject(micro_data))
return false;
$.each( micro_data, $.proxy(function(key,val) {
var breakpoint;
if(key === "srcportrait") {
breakpoint = key;
} else {
breakpoint = key.replace(/[A-Za-z$-]/g, "");
}
this.breakpoints[breakpoint] = val;
},this));
src = this.getBreakpointImage(win_width);
this.$el.on('load', $.proxy(function(e){
this.$el.trigger("breakpointer:changeImage", e.currentTarget);
if(dispatcher)
dispatcher.trigger("breakpointer:changeImage", e.currentTarget);
},this));
this.switchImg(src);
if(this.options.resizing) {
//needs refactoring.. every image has a callback;
$(window).on('resize orientationchange',$.proxy(function() {
this.image_source = this.getBreakpointImage($(window).width());
this.switchImg(this.image_source);
},this));
}
},
getBreakpointImage: function(width) {
var breakpoint_values = _.without( _.keys(this.breakpoints), 'srcportrait' ),
breakpoint_current;
breakpoint_current = _.min(breakpoint_values, function(num) {
if( width-parseInt(num) > 0)
return width-parseInt(num);
else
return 100000000000;
});
if($(window).width() < $(window).height() && this.breakpoints['srcportrait'])
return this.breakpoints['srcportrait'];
else
return this.breakpoints[breakpoint_current];
},
switchImg: function(src) {
if(this.$el.attr('src') != src )
this.$el.attr('src',src);
},
dfdChangeImg: function() {
var dfd = new $.Deferred();
this.$el.on("breakpointer:changeImage", function(){
dfd.resolve();
});
return dfd.promise();
}
};
$.fn['breakpointer'] = function ( options ) {
return this.each(function () {
if( !$.data(this,'breakpointer')) {
$.data( this, 'breakpointer', new BreakpointManager( this, options ));
}
});
};
})(jQuery, window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment