Skip to content

Instantly share code, notes, and snippets.

@en30
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save en30/24d4c5b901f453774358 to your computer and use it in GitHub Desktop.
Save en30/24d4c5b901f453774358 to your computer and use it in GitHub Desktop.
_ = require 'lodash'
module.exports = ({target, topBarrier, upperBound, bottomBarrier, lowerBound, wait, stickIf})->
getLowerBound = (topBarrier)->
return 0 unless topBarrier
topBarrier = topBarrier?() || topBarrier
topBarrierRect = topBarrier.getBoundingClientRect()
window.scrollY + topBarrierRect.bottom
getUpperBound = (bottomBarrier)->
return document.documentElement.getBoundingClientRect().height unless bottomBarrier
bottomBarrier = bottomBarrier?() || bottomBarrier
bottomBarrierRect = bottomBarrier.getBoundingClientRect()
window.scrollY + bottomBarrierRect.top
top = dy = 0
_.throttle(
->
return if typeof stickIf == 'function' and !stickIf()
oldDy = dy
dy = window.scrollY - top
top = window.scrollY
bottom = top + document.documentElement.clientHeight
target = target?() || target
targetRect = target.getBoundingClientRect()
targetTop = top + targetRect.top
targetBottom = top + targetRect.bottom
lb = lowerBound || getLowerBound(topBarrier)
ub = upperBound || getUpperBound(bottomBarrier)
cssText = if dy <= 0 && targetTop <= lb
"position: absolute; top: #{lb}px"
else if dy >= 0 && targetBottom >= ub
"position: absolute; top: #{ub - targetRect.height}px"
else if dy <= 0 && top < targetTop
"position: fixed; top: 0"
else if dy >= 0 && bottom > targetBottom
"position: fixed; bottom: 0"
else if dy * oldDy < 0
"position: absolute; top: #{targetTop}px"
target.style.cssText = cssText if cssText && target.style.cssText != cssText
wait
)
{
"name": "stickifier",
"version": "0.0.2",
"description": "Make elements sticky",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"postinstall": "coffee -bc main.coffee"
},
"repository": {
"type": "git",
"url": ""
},
"keywords": [
],
"author": "en30 <en30.git@gmail.com>",
"license": "MIT",
"dependencies": {
"lodash": "^2.4.1",
"coffee-script": "^1.8.0"
}
}
@en30
Copy link
Author

en30 commented Mar 22, 2015

How to install

package.json

{
  "dependencies": {
    "stickifer": "git+https://gist.github.com/en30/24d4c5b901f453774358"
  }
}

TODO

Tidy up

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment