softsprint menu Order

Smooth scrolling WordPress Script

July 9, 2016 in 6:05 pm | wiki

Hello!

Recently, I faced with the common for the WordPress sites task – it was necessary to make a smooth scroll to the target element on the page when you click on a link in the site menu. Actually, it is – the standard functionality of any modern Landing. In our case, the problem was to use pure JavaScript without connecting any frameworks like jQuery.
The network knows many WordPress plugins for smooth scrolling, for example: https://ru.wordpress.org/plugins/tags/smooth-scroll
But all of us know that the installation of any additional plugin in our site reduces its hacking security. In most cases, WordPress sites are hacked through the plugins – make conclusions!
So, the following code is written for a slow (smooth) scrolling on the page:

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
document.addEventListener("click", function (event) {
	var target = event.target;
	if (event.target.getAttribute("href")) {
		var targetHref = event.target.getAttribute("href")
	} else return false;
	if (targetHref.indexOf("#") >= 0) {
		var pos = targetHref.indexOf("#") + 1;
		var elemHref = document.getElementById(targetHref.slice(pos));
		moveScroll(elemHref);
		event.preventDefault()
	};
});
function moveScroll(elem) {
	var travel = 40;
	var time = 10;
	if (Math.abs(elem.getBoundingClientRect().top) < 1) return false;
	if (elem.getBoundingClientRect().top < 0) {
		if (Math.abs(elem.getBoundingClientRect().top) < travel) {
			window.scrollBy(0,-1);
			setTimeout(moveScroll,time/5,elem);
			} else {
			window.scrollBy(0,-travel);
			setTimeout(moveScroll,time,elem);
		}
	};
	if (elem.getBoundingClientRect().top > 0) {
		if (Math.abs(elem.getBoundingClientRect().top) < travel) {
			window.scrollBy(0,1);
			setTimeout(moveScroll,time/5,elem);
			} else {
			window.scrollBy(0,travel);
			setTimeout(moveScroll,time,elem);
		}
	}	
};

Scroll function recursively runs at intervals: time = 10 ms.
travel = 40 – the vertical scroll move at each recursive function call.
Presented script works for such kind of links:

1
<a href="http://softsprint.net/en/#about">About us</a>

The script is checking whether there is a link address to the element ID to which our page will be scrolled.

Thanks for the reading of our notes!

Let`s discuss

softsprint heart

Our contacts

Lviv, Ukraine
моб: +380 97 551 44 55
skype: softsprint.net

Say hello!