CSS solution
Anchor links bring us to sections of a page they link to instantaneously. We can replace this "teleportation" with smooth scrolling animation, using single CSS property:
html {
scroll-behavior: smooth;
}
Unfortunately this does not work on Safari. Truly, safari is a new IE6.
Javascript solution
Fortunately, we can achieve a smooth scrolling effect with a bit of jQuery code.
The snippet below simulates smooth anchor clicking with all its aspects. Thanks to use of history API, back and forward browser buttons work. If user starts scrolling while the animation is still running, it stops to avoid "fighting" with animation movement.
$('a[href^="#"]').on('click', function(event) {
var hash = '#' + $(this).attr('href').split('#')[1]
var element = $(hash)
if (element.length) {
event.preventDefault();
history.pushState(hash, undefined, hash)
$('html, body').animate({scrollTop: element.offset().top}, 500)
}
});
window.addEventListener('popstate', function(e) {
if(e.state && e.state.startsWith('#') && $(e.state).length){
$('html, body').animate({scrollTop: $(e.state).offset().top}, 500)
}
});
$('html, body').on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function(){
$('html, body').stop();
});
Top comments (5)
What is wrong with the teleportation? It makes browsing faster and needs less energy from my netbook batteries.
Yeah web site exists for the visitors...But for many products developers are not average user as well.
Some clients want such eye candy. Unfortunately webdevs don't rule the world.
But generally, the web site exists for the visitors, not for the owners. Isn't it?
If owners pays for a website, then a website exists for them.
Sometimes website needs to look as flashy as possible, and laptop battery be damned.