Skip to content

Instantly share code, notes, and snippets.

@ayozebarrera
Last active August 29, 2015 14:03
Show Gist options
  • Save ayozebarrera/a11b27fe8444015c8a4c to your computer and use it in GitHub Desktop.
Save ayozebarrera/a11b27fe8444015c8a4c to your computer and use it in GitHub Desktop.
A function that fit images to his parent
body img{
width: 100%; /* default */
}
img.fitWidth{
height: 100% !important;
width: auto !important;
}
fitImages: function(){
var screenImages = $("body img"); //select the img of the screen
$.each(screenImages, function(i, item) {
var theImage = new Image(); // Create new offscreen image to test
theImage.src = $(item).attr("src");
// Get accurate measurements from that.
theImage.onload = function() { //it will be 0x0 if you don't try to get the dimensions on the load
var imageWidth = this.width;
var imageHeight = this.height;
if (imageWidth > imageHeight)
$(item).addClass('fitWidth'); //check fitImages.css
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment