Skip to content

Instantly share code, notes, and snippets.

@khrome
Created September 6, 2012 22:08
Show Gist options
  • Save khrome/3660737 to your computer and use it in GitHub Desktop.
Save khrome/3660737 to your computer and use it in GitHub Desktop.
Element.optimalWidth
Element.implement({
// if called with callback, the element is set to the optimalWidth and called back when ready
// else the optimalWidth is calculated and returned
optimalWidth : function(callback){
var increment = 10;
var fuse = 10; //how many unchanged iterations before we're done?
var originalSize = this.getSize();
var lastForwardChange;
for(var lcv=0; lcv < fuse; lcv++){
var currentSize = this.getSize();
var newWidth = currentSize.x + increment;
this.setStyle('width', newWidth);
if(currentSize.y > this.getSize().y){ //smaller height
lastForwardChange = newWidth;
lcv = 0; //reset the loop if values are changing
}
}
if(lastForwardChange){
if(callback){
this.setStyle('width', lastForwardChange);
if(typeOf(callback) == 'function') callback();
}else{
this.setStyle('width', originalSize.x);
}
return lastForwardChange;
}
var lastBackwardUnchanged;
for(var lcv=0; lcv < fuse; lcv++){
var currentSize = this.getSize();
var newWidth = currentSize.x - increment;
this.setStyle('width', newWidth);
if(currentSize.y == this.getSize().y){
lastBackwardUnchanged = newWidth; //even height
lcv = 0; //reset the loop if values are changing
}else break;
}
if(lastBackwardUnchanged){
if(callback){
this.setStyle('width', lastBackwardUnchanged);
if(typeOf(callback) == 'function') callback();
}else{
this.setStyle('width', originalSize.x);
}
return lastBackwardUnchanged;
}
return currentSize.x; //exception?
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment