-
Notifications
You must be signed in to change notification settings - Fork 0
/
jQuery.keepInView.js
78 lines (65 loc) · 1.82 KB
/
jQuery.keepInView.js
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
66
67
68
69
70
71
72
73
74
75
76
77
78
(function($) {
// Do the scroll
$.fn.scrollIntoView = function(options, secondaryCallback) {
var defaults = {
topLimit: 0,
scrollSpeed: 500,
scrollType: "swing"
}
options = $.extend(defaults,options)
scrollTop = this.offset().top - options.topLimit
// This should fire the secondaryCallback. It should only happen once
var doCallback = function() {
if (typeof(secondaryCallback) === 'function') {
secondaryCallback()
}
}
if ($('html, body').scrollTop() !== scrollTop) {
$('html, body').animate({'scrollTop': scrollTop}, options.scrollSpeed, options.scrollType, doCallback)
}
// Make this chainable
return this
}
$.fn.keepInView = function(options) {
var docHeightTimer,
defaults = {
scrollSpeed: 0
},
docHeight = $(document).height(),
$el = this
options = $.extend(defaults,options)
var scrollWithoutBind = function() {
window.jQueryScrolling = true
$el.scrollIntoView(options, function() {
window.setTimeout(function() {
window.jQueryScrolling = false
}, 50)
})
}
var domModifiedWatch = function() {
if (docHeightTimer) {
window.clearTimeout(docHeightTimer)
}
docHeightTimer = window.setTimeout(function() {
var newHeight = $(document).height()
if (newHeight != docHeight) {
docHeight = newHeight
scrollWithoutBind()
}
}, 500)
}
var cancelDomModified = function() {
if (! window.jQueryScrolling) {
$(document).off('DOMSubtreeModified', domModifiedWatch)
$(window).off('scroll', cancelDomModified)
}
}
// If there is a scroll event, we want to cancel the anchor watch
$(window).on('scroll', cancelDomModified)
// If the document changes size, we want to...
$(document).on('DOMSubtreeModified', domModifiedWatch)
scrollWithoutBind()
// Make this chainable
return this
}
})(jQuery);