Last active
October 22, 2015 21:53
-
-
Save eric-miller2129/0456ed8b3cc7106580e3 to your computer and use it in GitHub Desktop.
Aspect Ratio Resize to container
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (function($){ | |
| 'use strict'; | |
| var AspectResize = function(elem, options){ | |
| var _this = this; | |
| _this.init = function(){ | |
| _this.containerWidth = elem.parent().outerWidth(); | |
| _this.containerHeight = elem.parent().outerHeight(); | |
| _this.options = $.extend({ | |
| verticalCenter: true, | |
| horizontalCenter: true | |
| }, options) | |
| /* | |
| | Hide the image first so it doesn't glitch when loading the page | |
| */ | |
| elem.css({opacity: 0}); | |
| /* | |
| | We have to wait for each image to load. This is a simple fix | |
| | the plugin will wait for the window to load and fix. | |
| */ | |
| $(window).on('load', function(){ | |
| _this.imageWidth = elem.width(); | |
| _this.imageHeight = elem.height(); | |
| _this.fixThatImage(); | |
| }); | |
| }; | |
| _this.fixThatImage = function(){ | |
| var ratio = 0; | |
| if(_this.imageWidth < _this.imageHeight){ | |
| ratio = _this.containerHeight / _this.imageHeight; | |
| elem.css({width: _this.imageWidth * ratio}); | |
| elem.css({height: _this.containerHeight}); | |
| }else if(_this.imageWidth < _this.imageHeight){ | |
| ratio = _this.containerWidth / _this.imageWidth; | |
| elem.css({width: _this.containerWidth}); | |
| elem.css({height: _this.imageHeight * ratio}); | |
| }else if(_this.imageWidth === _this.imageHeight){ | |
| elem.css({width: '100%', height: '100%'}); | |
| _this.showIt(); | |
| } | |
| if(_this.imageWidth !== _this.imageHeight){ | |
| _this.centerThisImage(); | |
| } | |
| }; | |
| _this.centerThisImage = function(){ | |
| elem.css({ | |
| position: 'absolute', | |
| top: (_this.options.verticalCenter) ? '50%' : 0, | |
| left: (_this.options.horizontalCenter) ? '50%' : 0, | |
| marginLeft: (_this.options.horizontalCenter) ? (elem.width() / 2)*-1 : 0, | |
| marginTop: (_this.options.verticalCenter) ? (elem.height() / 2)*-1 : 0, | |
| }); | |
| _this.showIt(); | |
| }; | |
| _this.showIt = function(){ | |
| elem.animate({ | |
| opacity: 1 | |
| }); | |
| } | |
| _this.init(); | |
| }; | |
| $.fn.aspectResize = function(options){ | |
| var instances = []; | |
| return this.each(function(){ | |
| var aspectResize = $(this); | |
| instances.push(new AspectResize(aspectResize, options)); | |
| }); | |
| }; | |
| }($)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment