CoffeeScript
by vjeux
HTML
<script src="https://github.com/jashkenas/coffee-script/raw/master/extras/coffee-script.js"></script>
<!-- New Anchor HTML attribute by Vjeux
data-anchor="[point], [relativeTo], [relativePoint], [x], [y]"
Allowed Points:
top left , top , top right
left , center , right
bottom left , bottom , bottom right
Allowed Relative:
Any jQuery CSS Selector
-->
<div id="frame"></div>
<!-- In order to put the sidebar centered at the right of the frame:
Sidebar.left = Frame.right -->
<div id="sidebar" data-anchor="left, #frame, right"></div>
<!-- In order to put the chat at the top right of the screen:
Chat.topRight = HTML.topRight + {x: -10, y: 10} -->
<div id="chat" data-anchor="top right, html, top right, -10, 10"></div>
CSS
#frame {
width: 100px;
height: 200px;
background-color: #333;
}
#sidebar {
width: 50px;
height: 120px;
background-color: red;
}
#chat {
width: 100px;
height: 100px;
background-color: blue;
}
body {
background-color: #111;
}
CoffeeScript
# Anchor by Vjeux
String::contains = (str) -> -1 isnt this.indexOf str
anchor = (elem) ->
# Parse the string
[point, relativeTo, relativePoint, x, y] = ($(elem).data 'anchor').split ','
$relativeTo = $ relativeTo
$elem = $ elem
weigth = (source, def, data) ->
for key, val of data
if source.contains key
return val
return def
# Calculate the new position
offset = $relativeTo.offset()
offset.left += $relativeTo.width() * weigth relativePoint, 0.5, left: 0, right: 1
offset.top += $relativeTo.height() * weigth relativePoint, 0.5, top: 0, bottom: 1
offset.left -= $elem.width() * weigth point, 0.5, left: 0, right: 1
offset.top -= $elem.height() * weigth point, 0.5, top: 0, bottom: 1
offset.left += parseInt(x) || 0
offset.top += parseInt(y) || 0
# Update the position
$elem.css
position: 'absolute'
top: offset.top
left: offset.left
# Find all elements with data-anchor
$('[data-anchor]').each -> anchor this