IE8 BG Image Module
// [data-bg-cover] is the attribute that powers this.
var $ = window.jQuery;
/**
* The Ie bg Shim Class.
* @param {Object} $el The jQuery Element
* @param {Number} i The index given for reference
*/
function IeBgImage ($el, i) {
// The Parent
this.$self = $el;
// Get the Image Url from the el
this.imgUrl = this.$self.attr('data-bg-cover');
// Make a new div > image to place in the parent
this.img = $('<div data-bg-img-'+i+'><img src="'+ this.imgUrl +'"></img></div>');
// get the sizes of the current el
this.size = {
height : this.$self.outerHeight(),
width : this.$self.outerWidth()
};
// calculate the ratio for later.
this.selfRatio = this.size.height / this.size.width;
// store the ratio
this.index = i;
}
/**
* Fired to calculate and make the magic happen.
*/
IeBgImage.prototype.init = function() {
// Get the img if it is already in the dom (recalculating).
this.$div = $('[data-bg-img-'+this.index+']').first();
// If not there lets add it to the dom and create the reference
if (this.$div.length < 1) {
this.$self.prepend(this.img);
this.$div = $('[data-bg-img-'+this.index+']').first();
}
// reference the img from the div for fun
this.$img = this.$div.find('img').first();
// calculate the ratio
var imgRatio = this.$img.height() / this.$img.width();
// use the ratio to set the height / width of the new image
var newHeight = imgRatio < this.selfRatio ? '100%' : 'auto' ;
var newWidth = imgRatio < this.selfRatio ? 'auto' : '100%';
// If this position isn't set to anything, lets make it relative
if (this.$self.css('position') === 'static') {
this.$self.css('position', 'relative');
}
// get rid of parents bg
this.$self.css({
"background" : "none !important",
});
// style the div to the right height / width and hide the overflow.
this.$div.css({
"display" : "block",
"width" : "100%",
"height" : this.size.height + 'px',
"overflow" : "hidden",
"z-index" : "0",
"position" : "absolute",
"top" : 0
});
// style the img and call it a day.
this.$img.css({
"position" : "absolute",
"top" : 0,
"z-index" : 0,
"height" : newHeight,
"width" : newWidth
});
};
module.exports = IeBgImage;
// Use this to do work
// var bgs = $('[data-bg-cover]');
// bgs.each( function(i) {
// var self = $(this);
// var ieBg = new IeBgImage(self, i);
// ieBg.init(); // Go baby
// });