-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjquery.stick.coffee
41 lines (36 loc) · 1.02 KB
/
jquery.stick.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
$ = jQuery
STATIC = 'static'
FIXED = 'fixed'
$.fn.stick = (args) -> s = new Stick(this, args)
class Stick
constructor: (@target, args) ->
@offset = if typeof args is "number" then args else 0
$.extend @, args if typeof args is "object"
@state = STATIC
@resize()
((s) -> $(window).scroll(-> s.scroll(this)).resize(-> s.resize(this)))(@)
position: ->
@target.css(
"position": @state
"top": @offset+"px"
"left": @targetLeft+"px"
)
resize: ->
@targetOffset = parseInt @target.offset().top
@targetLeft = parseInt @target.offset().left
targetBottom = @targetOffset + @target.height()
if $(window).height() < targetBottom
@disabled = true
@position() if @state is FIXED
else
@disabled = false
@scroll()
scroll: (self) ->
return if @disabled
if (@targetOffset - $(self).scrollTop()) - @offset <= 0
@onStick?() if @state is STATIC
@state = FIXED
else
@onUnstick?() if @state is FIXED
@state = STATIC
@position()