You've already started watching Smooth Scrolling in jQuery
In this Treehouse Quick Tip, Andrew Chalkley will take you through an example using jQuery's Smooth Scrolling on a FAQ page.
-
0:00
[Treehouse presents]
-
0:03
[Smooth Scrolling jQuery with Andrew Chalkley]
-
0:05
Hi, I'm Andrew.
-
0:07
In this Treehouse Quick Tip, we're going to use jQuery
-
0:10
to do some smooth scrolling on an FAQ page.
-
0:14
As you can see here, we've got a list of FAQs
-
0:17
and when you click on one, it jumps you down to the question and answer.
-
0:21
Instead of jumping from the link to the text,
-
0:23
it would be nice to scroll smoothly down to the answer.
-
0:27
This should also help the user get an idea
-
0:29
of where they are on the page as it scrolls.
-
0:32
Here in the code, we have a list of links.
-
0:35
Each of the links goes to one of the FAQs down the page.
-
0:38
If you notice, each of the link hrefs is exactly the same
-
0:42
as the id of the div surrounding an FAQ.
-
0:47
We can use jQuery to select the appropriate div when the link is pressed and scroll to it.
-
0:55
First let's select the links in the FAQs unordered list.
-
1:08
and then we want to bind a click handler to these links
-
1:11
and then finally get the contents of the href attribute.
-
1:21
We'll store this in a variable called FAQ id [faqId].
-
1:38
Next we want to select the body and use the animate method.
-
1:41
The animate method takes 2 parameters:
-
1:44
1) the options for the animation and 2) the speed.
-
1:52
We will fill in "slow" for the speed at the moment.
-
1:55
We're only concerned with the scrollTop option
-
1:58
which tells the selected element—in our case, the body—to scroll to the top
-
2:02
of a specified number of pixels.
-
2:09
We want this to be the top offset of our FAQ div, so let's select the correct div
-
2:14
with the faqId and use the offset method and the top attributes
-
2:19
to get the number of pixels offset.
-
2:30
Finally we want to return "false" to stop the browser's default behavior
-
2:33
of following the link and jumping to the page.
-
2:39
Now let's try that out.
-
2:41
So let's reload the page and see the results of what we've done.
-
2:46
As you can see when we click on these links now,
-
2:49
the page scrolls nicely and smoothly to the correct FAQ.
-
2:53
And that's it—without altering a line of HTML,
-
2:56
we've used jQuery to give a nice polish to the user experience.
You need to sign up for Treehouse in order to download course files.
Sign up