Skip to content

Instantly share code, notes, and snippets.

@ivanmarkovich
Created February 25, 2019 09:07
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 ivanmarkovich/c64adf07a047ce976338fcade8d89a6f to your computer and use it in GitHub Desktop.
Save ivanmarkovich/c64adf07a047ce976338fcade8d89a6f to your computer and use it in GitHub Desktop.
img cover
// img cover
var imageCoverFunc = function() {
//set size
var th = $(this).height(),//box height
tw = $(this).width(),//box width
im = $(this).children('img'),//image
ih = im.height(),//inital image height
iw = im.width();//initial image width
if ((th/tw) > (ih/iw)){
im.addClass('wh').removeClass('ww');//set height 100%
} else {
im.addClass('ww').removeClass('wh');//set width 100%
}
//set offset
var nh = im.height(),//new image height
nw = im.width(),//new image width
hd = (nh-th)/2,//half dif img/box height
wd = (nw-tw)/2;//half dif img/box width
if (hd < 1) {hd = 0;}
if (wd < 1) {wd = 0;}
im.css({marginLeft: '-'+wd+'px', marginTop: '-'+hd+'px'});//offset left
}
// $('.img-cover img')[0].addEventListener('load', function() {
// $(this).closest('.img-cover').each(imageCoverFunc);
// }, false);
$('.img-cover img').each(function(){
if ( !this ) return;
this.addEventListener('load', function() {
$(this).closest('.img-cover').each(imageCoverFunc);
}, false);
})
$('.img-cover').each(imageCoverFunc);
window.onresize = function(){
$('.img-cover').each(imageCoverFunc);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment