Skip to content

Instantly share code, notes, and snippets.

@robertcasanova
Last active December 18, 2015 02:59
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/5714889 to your computer and use it in GitHub Desktop.
Save robertcasanova/5714889 to your computer and use it in GitHub Desktop.
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;
};
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.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 = _.keys(this.breakpoints),
breakpoint_current;
breakpoint_current = _.min(breakpoint_values, function(num) {
return Math.abs(num-width);
});
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);
}
};
$.fn['breakpointer'] = function ( options ) {
return this.each(function () {
new BreakpointManager( this, options ).init();
});
};
})(jQuery, window, document);
<img class="front-img"
src="{{ image| imagine_filter('breakpoint_placeholder') }}"
data-src700="{{ image| imagine_filter('breakpoint_small') }}"
data-src1200="{{ image| imagine_filter('breakpoint_medium') }}"
data-src1600="{{ image| imagine_filter('breakpoint_large') }}"
data-srcPortrait="{{ image| imagine_filter('breakpoint_medium') }}"
alt="">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment