Skip to content

Instantly share code, notes, and snippets.

@shanejdonnelly
Created June 12, 2012 17:33
Show Gist options
  • Save shanejdonnelly/2918907 to your computer and use it in GitHub Desktop.
Save shanejdonnelly/2918907 to your computer and use it in GitHub Desktop.
A plugin to simulate background:cover in IE
/*
* Plugin Name : imgResize
* Author : Shane Donnelly
*/
(function($){
//here's our resizer object
$.Resize = function (el, options) {
this.options = options;
this.$el = $(el);
this.init();
};
//initialize the plugin
$.Resize.prototype.init = function () {
var base = this;
base.settings = $.extend({}, base.defaults, base.options);
base.image = $('<img />')
.attr('src', base.settings.img_url)
.attr('style', 'position:fixed;display:block;top:'+ base.settings.top_offset +'px;')
.load(function(){
base.$el
.css('background','none')
.append(base.image);
base.img_width = base.image.width();
base.img_height = base.image.height();
base.scaleImage();
$(window).resize(function(){
base.scaleImage();
});
});
}
$.Resize.prototype.scaleImage = function(){
var base = this,
window_width = $(window).width(),
window_height = $(window).height(),
width_ratio = window_width/base.img_width,
height_ratio = window_height/base.img_height,
temp_height = 0,
temp_width = 0,
left = 0;
if(width_ratio > height_ratio){
//make image width equal windowWidth
base.$el.find('img').css('width',window_width);
temp_height = base.img_height * width_ratio;
base.$el.find('img').css('height',temp_height);
base.$el.find('img').css('left', left);
}
else{
base.$el.find('img').css('height',window_height);
temp_width = base.img_width * height_ratio;
base.$el.find('img').css('width',temp_width);
if(base.settings.position === 'center'){
left = (temp_width - window_width)/2;
base.$el.find('img').css('left','-'+ left + 'px');
}
else{ //position === 'left'
base.$el.find('img').css('left', left);
}
}
}
//default plugin options
$.Resize.prototype.defaults = {
img_url : '',
top_offset : 0,
position : 'center' //left, center
};
//the jQuery plugin call
$.fn.imgResize = function(options) {
return this.each(function() {
new $.Resize(this, options);
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment