# 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
<!-- 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">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">Sidebar</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">Chat</div>
#frame { width: 100px; height: 200px; background-color: #333; } #sidebar { width: 70px; height: 120px; background-color: red; } #chat { width: 100px; height: 100px; background-color: blue; } body { background-color: #111; } div { color: #eee; font-family: Tahoma; font-size: 11px; text-align: center; }