jQuery Smooth Scroll to Anchor
29 Sep, '16snippets• 1 min.
We all know that jQuery is a brilliant Javascript library, which can be used to add interactivity to our web pages.
One such interactivity is smoothly scrolling to the appropriate section of your page on clicking a link… Smoooov, right?
The following jQuery snippet can be used to achieves this:
What is happening here?
a[href*="#"]:not([href="#"])
targets all anchors.
On click, it checks that the link is pointing to same page and same domain: (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname).
Remainder of the script sets up the target
, then uses scrollTop();
and animate();
to smoothly scroll the web page to that section.
Hopefully this is helpful… Do not hesitate to post any improvements.