Skip to content

Instantly share code, notes, and snippets.

@anson0370
Created June 10, 2013 07:58
Show Gist options
  • Save anson0370/5747175 to your computer and use it in GitHub Desktop.
Save anson0370/5747175 to your computer and use it in GitHub Desktop.
a jquery plugin to pin an element on any element u want
do ($=jQuery) ->
$.fn.pin = (target) ->
$target = if target
if typeof target == "function"
target.apply @
else
$(target)
else
$(@).parent()
originTop = $(@).offset().top
targetBottom = $target.offset().top + $target.height()
$(window).scroll =>
if ($(@).offset().top + $(@).height()) > targetBottom
$(@).css
position: "absolute"
top: targetBottom - $(@).height()
return
if $(@).offset().top < originTop
$(@).css
position: "static"
return
if $(@).offset().top < $(window).scrollTop() and ($(@).offset().top + $(@).height()) < targetBottom
$(@).css
position: "fixed"
top: 0
return
if $(@).offset().top > $(window).scrollTop() and $(@).offset().top > originTop
$(@).css
position: "fixed"
top: 0
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment