Skip to content

Instantly share code, notes, and snippets.

@GCheung55
Last active December 14, 2015 07:49
Show Gist options
  • Save GCheung55/5053726 to your computer and use it in GitHub Desktop.
Save GCheung55/5053726 to your computer and use it in GitHub Desktop.
"use strict"
var $ = require("elements")
var relativeMap = {
right: 'left',
bottom: 'top'
}
var relativeExclude = ['width', 'height']
$.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 (relativeExclude.indexOf(prop) == -1 ) 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