Search code examples
javascriptjqueryscrollhyperlinkanchor

Smooth scrolling when clicking an anchor link


I have a couple of hyperlinks on my page. A FAQ that users will read when they visit my help section.

Using Anchor links, I can make the page scroll towards the anchor and guide the users there.

Is there a way to make that scrolling smooth?

But notice that he's using a custom JavaScript library. Maybe jQuery offers somethings like this baked in?


Solution

  • The new hotness in CSS3. This is a lot easier than every method listed on this page and requires no Javascript. Just enter the below code into you css and all of a sudden links point to locations inside you own page will have a smooth scrolling animation.

    html { scroll-behavior: smooth; }
    

    After that any links pointed towards a div will smoothly glide over to those sections.

    <a href="#section">Section1</a>
    

    Edit: For those confused about the above a tag. Basically it's a link that's clickable. You can then have another div tag somewhere in your web page like

    <div id="section">content</div>
    

    In this regard the a link will be clickable and will go to whatever #section is, in this case it's our div we called section.

    BTW, I spent hours trying to get this to work. Found the solution in some obscure comments section. It was buggy and wouldn't work in some tags. Didn't work in the body. It finally worked when I put it in html{} in the CSS file.