forked from GabrielDelepine/smooth-scroll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmooth-scroll.js
75 lines (66 loc) · 3.05 KB
/
smooth-scroll.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
/*
* - autoSmoothScroll -
* Licence MIT
* Written by Gabriel Delépine
* Current version 1.3.1 (2014-10-22)
* Previous version 1.3.0 (2014-07-23)
* Previous version 1.2.0 (2014-02-13)
* Previous version 1.0.1 (2013-11-08)
* Previous version 1.0.0 (2013-10-27)
* Requirement : None, it is a framework-free function (i.e. you do not need to include any other file in your page such as jQuery)
* Fork-me on github : https://github.com/Yappli/smooth-scroll
* */
(function(window, undefined) // Code in a function to create an isolate scope
{
'use strict';
var height_fixed_header = 0, // For layout with header with position:fixed. Write here the height of your header for your anchor don't be hiden behind
speed = 500,
moving_frequency = 15, // Affects performance ! High number makes scroll more smooth
links = document.getElementsByTagName('a'),
href;
for(var i = 0; i < links.length; i++)
{
href = (links[i].attributes.href === undefined) ? null : links[i].attributes.href.nodeValue.toString();
if(href !== null && href.length > 1 && href.indexOf('#') != -1) // href.substr(0, 1) == '#'
{
links[i].onclick = function()
{
var element,
href = this.attributes.href.nodeValue.toString(),
url = href.substr(0, href.indexOf('#')),
id = href.substr(href.indexOf('#') + 1);
if (element = document.getElementById(id))
{
var hop_count = (speed - (speed % moving_frequency)) / moving_frequency, // Always make an integer
getScrollTopDocumentAtBegin = getScrollTopDocument(),
gap = (getScrollTopElement(element) - getScrollTopDocumentAtBegin) / hop_count;
if (window.history && typeof window.history.pushState == 'function')
window.history.pushState({}, undefined, url + '#' + id); // Change URL for modern browser
for (var i = 1; i <= hop_count; i++)
{
(function()
{
var hop_top_position = gap * i;
setTimeout(function(){ window.scrollTo(0, hop_top_position + getScrollTopDocumentAtBegin); }, moving_frequency * i);
})();
}
return false;
}
};
}
}
var getScrollTopElement = function(e)
{
var top = height_fixed_header * -1;
while (e.offsetParent != undefined && e.offsetParent != null)
{
top += e.offsetTop + (e.clientTop != null ? e.clientTop : 0);
e = e.offsetParent;
}
return top;
};
var getScrollTopDocument = function()
{
return window.pageYOffset !== undefined ? window.pageYOffset : document.documentElement.scrollTop !== undefined ? document.documentElement.scrollTop : document.body.scrollTop;
};
})(window);