Dynamic Aspect Ratio

by Anov Siradj

HTML

Change Aspect Ratio:
<input placeholder="WIDTH"/> by <input placeholder="HEIGHT"/>
<hr/>

<div class="das-outer" style="--w: 16;--h: 9;background: red;">
  <div class="das-inner" style="overflow-y: auto;/*for content text*/">
		Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
		tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
		quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
		consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
		cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
		proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
</div>
<hr/>
<small>/anovsiradj</small>

CSS

.das-outer {
  position: relative;
  display: block;
  width: 100%;
  padding-top: calc(100% * (var(--h)) / var(--w));
}
.das-outer > .das-inner {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

JavaScript

/*
[Reference] Thanks to:
https://developer.mozilla.org/en-US/docs/Web/CSS/calc
https://developer.mozilla.org/en-US/docs/Web/CSS/--*
https://developer.mozilla.org/en-US/docs/Web/CSS/var
https://css-tricks.com/snippets/sass/maintain-aspect-ratio-mixin/
http://www.mademyday.de/css-height-equals-width-with-pure-css.html
https://alistapart.com/article/creating-intrinsic-ratios-for-video
*/

var a = document.body.querySelectorAll('input');
var delay = Math.floor(1000/3);
var width = a[0], height = a[1], outer = document.body.querySelector('.das-outer'), inner = document.body.querySelector('.das-inner');

width.addEventListener('keyup', debounce(function() {
	var value = Number(width.value);
	if(isNaN(value) || value < 1) return;
	outer.style.setProperty('--w', value);
}, delay));

height.addEventListener('keyup', debounce(function() {
	var value = Number(height.value);
	if(isNaN(value) || value < 1) return;
	outer.style.setProperty('--h', value);
}, delay));

// https://gist.github.com/nmsdvid/8807205
function debounce(a,b,c){var d;return function(){var e=this,f=arguments;clearTimeout(d),d=setTimeout(function(){d=null,c||a.apply(e,f)},b),c&&!d&&a.apply(e,f)}}