-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscroll-to-anchor.js
69 lines (46 loc) · 1.83 KB
/
scroll-to-anchor.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
/**
* @preserve
* jQuery Scroll To Anchor
* Copyright (c) Karsten Müller
*/
/**
* jQuery Plugin which adds a smooth scrolling animation to “anchor links”,
* means links which point to an internal target location within the current HTML document.
*/
(function ( $ ){
var defaults = {
speed: 3000, // Scrolling speed (in pixels per second)
duration_min: 200, // Minimum duration (in ms)
selector: "a[href^='#'], a[href^='/#']" // Selector for triggers
};
$.fn.scrollToAnchor = function(options){
var options = options || {};
return this.each(function(){
var container = $(this),
settings = $.extend({}, defaults, options);
if ($(settings.selector, container).length !== 0){
$(settings.selector, container).each(function(e){
var id = $(this).attr("href").replace(/.*#/, "");
$(this).click(function(e){
e.preventDefault();
if (id === "" || $("#" + id).length === 0){
var top = 0;
} else {
var top = $("#" + id).offset().top;
}
var distance = Math.abs($(window).scrollTop() - top);
var duration = distance/settings.speed * 1000;
duration = duration < settings.duration_min ? settings.duration_min : duration;
$("html, body").animate(
{ scrollTop: top },
duration,
function(){
location.hash = id;
}
);
});
});
}
});
}
}( jQuery ));