Skip to content

Instantly share code, notes, and snippets.

@n3o77
Forked from GCheung55/dimensions.js
Created February 28, 2013 02:43
Show Gist options
  • Save n3o77/5053758 to your computer and use it in GitHub Desktop.
Save n3o77/5053758 to your computer and use it in GitHub Desktop.
"use strict"
var $ = require("elements")
var relativeMap = {
right: 'left',
bottom: 'top'
}
$.implement({
position: function(relative){
var node = this[0], box = {left: 0, right: 0, top: 0, bottom: 0},
win = window, doc = node.ownerDocument,
docElem = doc.documentElement,
body = doc.body
if (typeof node.getBoundingClientRect !== "undefined"){
box = node.getBoundingClientRect()
}
var clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || docElem.scrollTop,
scrollLeft = win.pageXOffset || docElem.scrollLeft,
dx = scrollLeft - clientLeft,
dy = scrollTop - clientTop
var pos = {
x: box.left + dx, left: box.left + dx,
y: box.top + dy, top: box.top + dy,
right: box.right + dx, bottom: box.bottom + dy,
width: box.right - box.left,
height: box.bottom - box.top
}
if (relative && (relative = $(relative))) {
var rp = relative.position()
for(var prop in pos){
if (prop != "width" || prop != "height") pos[prop] = pos[prop] - rp[ prop in relativeMap ? relativeMap[prop] : prop ]
}
}
return pos
}
})
module.exports = $
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment