sticky.js
1.76 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*!
Waypoints Sticky Element Shortcut - 3.0.0
Copyright © 2011-2014 Caleb Troughton
Licensed under the MIT license.
https://github.com/imakewebthings/waypoints/blog/master/licenses.txt
*/
(function() {
'use strict'
var $ = window.jQuery
var Waypoint = window.Waypoint
/* http://imakewebthings.com/waypoints/shortcuts/sticky-elements */
function Sticky(options) {
this.options = $.extend({}, Waypoint.defaults, Sticky.defaults, options)
this.element = this.options.element
this.$element = $(this.element)
this.createWrapper()
this.createWaypoint()
}
/* Private */
Sticky.prototype.createWaypoint = function() {
var originalHandler = this.options.handler
this.waypoint = new Waypoint($.extend({}, this.options, {
element: this.wrapper,
handler: $.proxy(function(direction) {
var shouldBeStuck = this.options.direction.indexOf(direction) > -1
var wrapperHeight = shouldBeStuck ? this.$element.outerHeight(true) : ''
this.$wrapper.height(wrapperHeight)
this.$element.toggleClass(this.options.stuckClass, shouldBeStuck)
if (originalHandler) {
originalHandler.call(this, direction)
}
}, this)
}))
}
/* Private */
Sticky.prototype.createWrapper = function() {
this.$element.wrap(this.options.wrapper)
this.$wrapper = this.$element.parent()
this.wrapper = this.$wrapper[0]
}
/* Public */
Sticky.prototype.destroy = function() {
if (this.$element.parent()[0] === this.wrapper) {
this.waypoint.destroy()
this.$element.removeClass(this.options.stuckClass).unwrap()
}
}
Sticky.defaults = {
wrapper: '<div class="sticky-wrapper" />',
stuckClass: 'stuck',
direction: 'down right'
}
Waypoint.Sticky = Sticky
}())
;