Skip to content

Instantly share code, notes, and snippets.

@yesasha
Last active August 29, 2015 14:16
Show Gist options
  • Save yesasha/bb7d7f97885068bc941d to your computer and use it in GitHub Desktop.
Save yesasha/bb7d7f97885068bc941d to your computer and use it in GitHub Desktop.
Keep Aspect Ratio
// Keeps aspect ratio of an element by listening to window resize event
// and setting height = width / aspect ratio
//
// Copyright (c) 2015 Aleksandr Efremov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Compress with GCC --compilation_level ADVANCED_OPTIMIZATIONS
// Usage: keep(ID, ratio); // Start listener
// keep(ID); // Stop listener
(function () {
var addEventListener = window.addEventListener;
var initValue = {};
var handlers = {};
keep = function (ID, ratio) {
var element = document.getElementById(ID);
var elementStyle = element.style;
if (!element) return;
if (!addEventListener) return;
removeEventListener('resize', handlers[ID], false);
delete handlers[ID];
// If started first time, there is no initial value
if (initValue[ID] !== undefined) {
// If there is initial value, then it was already started with the ratio argument
elementStyle.height = initValue[ID];
// Do it only once
delete initValue[ID];
}
// Stops listener if called without ratio argument
if (!ratio) return;
// We are going to start the listener, so save the height value
initValue[ID] = elementStyle.height;
// Save the handler, to be able to stop it the next time
handlers[ID] = handler;
addEventListener('resize', handler);
// The callback will fire on resize, but we want it the first time to fire immediately
handler();
// A handler
function handler () {
elementStyle.height = (parseFloat(getComputedStyle(element, null).width) / ratio) + 'px';
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment