SOFT
SPRINT

softsprint.net Shop

Smooth scrolling WordPress Script

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:

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:

About us

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!

CONTACT US
Cookies | Privacy Policy | Terms and ConditionsSoftSprint ©