-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjquery.offset-scroller.js
More file actions
63 lines (51 loc) · 1.5 KB
/
Copy pathjquery.offset-scroller.js
File metadata and controls
63 lines (51 loc) · 1.5 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
// jQuery offsetScroller
// Copyright (c) 2016 Mason Hale
// MIT License
(function($) {
function scrollToHash( hash, options ) {
var opts = $.extend( {}, $.fn.offsetScroller.defaults, options );
if (hash && hash[0] === '#') {
var targetObj;
try {
targetObj = $(hash);
}
catch(e) {
console.log("offsetScroller could not scroll to: '" + hash + "'");
}
var targetOffset = targetObj && targetObj.offset();
if (targetOffset) {
$('html, body').animate(
{scrollTop: (targetOffset.top - opts.offsetPixels)},
opts.animationSpeed);
return true;
}
}
return false;
}
function updateUrl( hash ) {
if ( history.pushState && window.location.protocol !== 'file:' ) {
history.pushState( null, null, hash );
}
}
function clickHandler( event ) {
// Don't run if right-click or command/control + click
if ( event.button !== 0 || event.metaKey || event.ctrlKey ) return;
var targetSel = $(this).attr("href");
if ( targetSel && targetSel[0] === '#' ) {
var opts = event.data;
event.preventDefault();
updateUrl( targetSel );
scrollToHash( targetSel, opts );
}
}
$.fn.offsetScroller = function( options ) {
return this.each( function() {
$(this).bind( 'click', options, clickHandler );
});
};
$.fn.offsetScroller.defaults = {
offsetPixels: 0,
animationSpeed: 500
}
$.fn.offsetScroller.scrollToHash = scrollToHash;
})(jQuery);