1/** 2 * imagefill.js 3 * Author & copyright (c) 2013: John Polacek 4 * johnpolacek.com 5 * https://twitter.com/johnpolacek 6 * 7 * Dual MIT & GPL license 8 * 9 * Project Page: http://johnpolacek.github.io/imagefill.js 10 * 11 * The jQuery plugin for making images fill their containers (and be centered) 12 * 13 * EXAMPLE 14 * Given this html: 15 * <div class="container"><img src="myawesomeimage" /></div> 16 * $('.container').imagefill(); // image stretches to fill container 17 * 18 * REQUIRES: 19 * imagesLoaded - https://github.com/desandro/imagesloaded 20 * 21 */ 22 ;(function($) { 23 24 $.fn.imagefill = function(options) { 25 26 var $container = this, 27 imageAspect = 1/1, 28 containersH = 0, 29 containersW = 0, 30 defaults = { 31 runOnce: false, 32 target: 'img', 33 throttle : 200 // 5fps 34 }, 35 settings = $.extend({}, defaults, options); 36 37 var $img = $container.find(settings.target).addClass('loading').css({'position':'absolute'}); 38 39 // make sure container isn't position:static 40 var containerPos = $container.css('position'); 41 $container.css({'overflow':'hidden','position':(containerPos === 'static') ? 'relative' : containerPos}); 42 43 // set containerH, containerW 44 $container.each(function() { 45 containersH += $(this).outerHeight(); 46 containersW += $(this).outerWidth(); 47 }); 48 49 // wait for image to load, then fit it inside the container 50 $container.imagesLoaded().done(function(img) { 51 imageAspect = $img.width() / $img.height(); 52 $img.removeClass('loading'); 53 fitImages(); 54 if (!settings.runOnce) { 55 checkSizeChange(); 56 } 57 }); 58 59 function fitImages() { 60 containersH = 0; 61 containersW = 0; 62 $container.each(function() { 63 imageAspect = $(this).find(settings.target).width() / $(this).find(settings.target).height(); 64 var containerW = $(this).outerWidth(), 65 containerH = $(this).outerHeight(); 66 containersH += $(this).outerHeight(); 67 containersW += $(this).outerWidth(); 68 69 var containerAspect = containerW/containerH; 70 if (containerAspect < imageAspect) { 71 // taller 72 $(this).find(settings.target).css({ 73 width: 'auto', 74 height: containerH, 75 top:0, 76 left:-(containerH*imageAspect-containerW)/2 77 }); 78 } else { 79 // wider 80 $(this).find(settings.target).css({ 81 width: containerW, 82 height: 'auto', 83 top:-(containerW/imageAspect-containerH)/2, 84 left:0 85 }); 86 } 87 }); 88 } 89 90 function checkSizeChange() { 91 var checkW = 0, 92 checkH = 0; 93 $container.each(function() { 94 checkH += $(this).outerHeight(); 95 checkW += $(this).outerWidth(); 96 }); 97 if (containersH !== checkH || containersW !== checkW) { 98 fitImages(); 99 } 100 setTimeout(checkSizeChange, settings.throttle); 101 } 102 103 return this; 104 }; 105 106}(jQuery));
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.