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