Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Konrad Pilch
Konrad Pilch
2,435 Points

Smooth Scrolling with jQuery not working

Hi,

What doesn't work?

$("#links a").click(function(){
                var linksId = $(this).attr("href");
                $("body").animate({scrollTop: $(linksId).offset().top}, "slow");

                return false;
            });

It works on Chrome but not on Mozilla or explorer . Not even the link if I click , it doesn't even put me on top of the webpage . I mean if I clikc Contact, it would scroll down, if I woudnt have the $ it would teleport there. But it doesn't even do that.

3 Answers

Hey Konrad,

Instead of using the href value, use the link's hash. I tested this in Chrome and Firefox:

$("#links a").click(function(e){       
    e.preventDefault();
    $('html,body').animate({scrollTop:$(this.hash).offset().top}, "slow");
});
Konrad Pilch
Konrad Pilch
2,435 Points

Thank u! Working. My code was from treehouse: d

OSCAR AU
OSCAR AU
14,008 Points

I tried using this on my navigation, but it also disables my link to another page.

But if I take out the e.preventDefault(); Then it gets a bit buggy.

Help anybody?

Tomáš Komprs
Tomáš Komprs
14,057 Points

This is an old topic, but I have right now a similar problem. And the best solution for me? Use this in CSS:

html {
    scroll-behavior: smooth;
}