Skip to content

Instantly share code, notes, and snippets.

@comfuture
Created December 17, 2013 06:47
Show Gist options
  • Save comfuture/8001025 to your computer and use it in GitHub Desktop.
Save comfuture/8001025 to your computer and use it in GitHub Desktop.
class Layout
###
> Layout.arrange('.home', {'bottom': 10})
// arrange all '.home' to bottom of their parent element
> Layout.arrange('.home', {'bottom': 10}).watch()
// arrange and monitor window resizing
> $('.home').arrange({'bottom': 30}).watch()
// using jquery direct
> $('.half').arrange({'height': '50%'}).watch();
// will always resized to 50 percent height
###
instance = null
watchList = []
constructor: ->
$(window).on 'resize', -> Layout.fit()
@
cssValue = (v)->
# XXX: only px or % is valuable
[_, value] = /^([0-9]+)(?:px|%)?/.exec(String(v))
value
@arrange: (el, spec)->
for _el in $(el).css(position: 'absolute')
$el = $(_el)
parent = $el.parent()
$el.css(width: $el.css('width'),
height: $el.css('height'))
if 'top' of spec
$el.css top: cssValue spec.top
else if 'bottom' of spec
$el.css top: parent.outerHeight() - cssValue(spec.bottom) - $el.outerHeight()
if 'left' of spec
$el.css top: cssValue spec.left
else if 'right' of spec
$el.css top: parent.outerWidth() - cssValue(spec.right) - $el.outerWidth()
if 'center' of spec
$el.css left: parent.outerWidth() / 2 - $el.outerWidth() / 2 + spec.center
if 'middle' of spec
$el.css top: parent.outerHeight() / 2 - $el.outerHeight() / 2 + spec.middle
if 'width' of spec
$el.css width: spec.width
if 'height' of spec
if /%/.test(String(spec.height))
$el.css height: parent.outerHeight() * cssValue(spec.height) * .01
else spec.height
if not instance
instance = new Layout()
watch: =>
watchList.push [el, spec]
@fit: ->
for [el, spec] in watchList
Layout.arrange el, spec
$?.fn?.arrange = (spec)-> Layout.arrange.call @, @, spec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment