Created
September 6, 2012 22:08
-
-
Save khrome/3660737 to your computer and use it in GitHub Desktop.
Element.optimalWidth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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