Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
var BalancedMeasures = {
minimumScreenSizeToRunOn: 992,
classNameToBalance: "graf--pullquote",
run: function(classToRunOn){
if(this.onSmallerScreen()){return;}
var elements = this.getElementsToBalance(classToRunOn);
for(var i = 0; i < elements.length; i++){
this.balance(elements[i]);
}
},
onSmallerScreen: function(){
var body = document.getElementsByTagName("body")[0];
var bodyWidth = parseFloat(window.getComputedStyle(body, null).getPropertyValue('width'));
return bodyWidth < this.minimumScreenSizeToRunOn;
},
getElementsToBalance: function(classToRunOn){
if(typeof(classToRunOn) === 'undefined'){classToRunOn = this.classNameToBalance;}
return document.getElementsByClassName(classToRunOn);
},
balance: function(element){
var originalStyle = window.getComputedStyle(element);
var originalHeight = parseInt(originalStyle.height, 10);
var originalWidth = parseInt(originalStyle.width, 10);
var originalMargins = parseInt(originalStyle.marginLeft, 10);
var originalTransition = originalStyle.transition;
var height = originalHeight;
var width = originalWidth;
var boxCanBeShrunk = true;
var boxIsTooTall = false;
var differenceInMarginWidth, newMargin;
element.style.transition = "";
while(boxCanBeShrunk){
width = width - 100;
element.style.width = ""+width+"px";
height = parseInt(window.getComputedStyle(element).height, 10);
if(height > originalHeight){
boxCanBeShrunk = false;
boxIsTooTall = true;
}
}
while(boxIsTooTall){
width = width + 10;
element.style.width = ""+width+"px";
height = parseInt(window.getComputedStyle(element).height, 10);
if(height <= originalHeight){
boxIsTooTall = false;
}
}
differenceInMarginWidth = (originalWidth - width)/2;
newMargin = originalMargins + differenceInMarginWidth;
element.style.marginLeft = ""+newMargin+"px";
element.style.marginRight = ""+newMargin+"px";
element.style.transition = originalTransition;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment