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

How to snap page to right place on click

If i was to click on a button for example how would i make the page scroll down to the relevant part of the page?

2 Answers

You don't really need JavaScript for that (unless you want a smooth scroll).

You create a regular link:

<a href="#idOfTheElementYouWantToSnapTo></a>

And then make sure the div (or any other element) has the id you specified in the anchor element.

You can check out an example here.

However, if you need a smooth scroll, you can use something like this.

Thank you for the help!

You accomplish this by using id's on the elements. Actually, it does not require JavaScript at all, if you simply want to jump to a specific element. Although, if you want it to neatly scroll to the element, it requires a tiny bit of JavaScript.

For the ease of the example I am going to use a link instead of a button. You can use a button if you want, but in my opinion it would be better to style your link as a button.

For the link you would use the following code. The # indicates id, as it does in CSS. This tells the browser that if the link is clicked, it is to jump to the element with the id "mycontent".

<a href="#mycontent">Jump to the content!</a>

Then, further down the page (or further up), you would have an element with the id "mycontent".

<div id="mycontent">Content has been jumped to.</div>

And thus, if you place the relevant part of the page in that div, you will have successfully snapped the page to the right place on click.

As I said at the start, if you're looking for the smooth scroll effect, you need JavaScript. You can Google around, but if you're using jQuery, this little snippet is very handy, and does the job nicely: http://css-tricks.com/snippets/jquery/smooth-scrolling/

Best of luck to you.