broken resize algorithm
by Emily Humphrey
HTML
<div class="js-ratio">
</div>
<div class="js-ratio" data-ratio="2:1">
</div>
CSS
div{
background: #ccc;
margin: 10px 0;
}
JavaScript
AspectRatio.prototype = {
init: function(){
// parent reference
var parent = this;
// external stylesheet reference
parent.styleReference = parent.element.currentStyle || window.getComputedStyle(parent.element);
// get desired ratio element
parent.ratio = parent.ratio || "16:9";
parent.ratio = parent.ratio.split(":");
// get current dimensions for element, either inline or external
parent.width = parent.element.style.width || parent.styleReference.width; // get original width of element
parent.height = parent.element.style.height || parent.styleReference.height; // get original height of element
// apply it to the element
parent.applyAdjustments(parent.findAdjustments());
$(window).on("resize", function(){
parent.applyAdjustments(parent.findAdjustments());
})
},
findAdjustments: function(){
// parent reference
var parent = this;
// get element's actual dimensions
var width = parent.element.offsetWidth,
height = parent.element.offsetHeight;
// get element's base dimensions
var rW = width/parent.ratio[0],
rH = height/parent.ratio[1];
// Get element's dominate value, either height or width
var dominateValue = rH > rW ? "height" : "width";
// return object
console.log(parent.ratio[0])
return {dominate: dominateValue, height: Math.round(rH*parent.ratio[0])+"px", width: Math.round(rW*parent.ratio[1])+"px"};
},
applyAdjustments: function(adjustments){
// parent reference
var parent = this;
if(adjustments.dominate == "height"){
return parent.element.style.width = adjustments.height;
} else{
return parent.element.style.height = adjustments.width;
}
}
};
function AspectRatio($element){
this.$element = $element;
this.element = $element[0];
this.ratio = $element.data("ratio");
this.init();
}
$(".js-ratio").each(function(){
new AspectRatio($(this));
});