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
Colin Marshall
32,861 PointsLinks to same page
So I am well aware how to link to a section of the same document using ID's. My problem is that I have a sticky navigation which isn't accounted for so it scrolls to the correct position when I click on the link, but the sticky navigation covers up the top part so it appears like it scrolls slightly too far.
Is there a way to offset where the link scrolls to so I can account for the sticky navigation?
2 Answers
Kevin Korte
28,149 PointsYou can, and possibly even without javascript. Here, look at this very simple code pen I made.
http://codepen.io/anon/pen/DpFEj
I think this is the end result you were going for. I found this page that offers some none CSS solutions, and the drawbacks of each. The solution in the codepen might not work for you.
http://nicolasgallagher.com/jump-links-and-viewport-positioning/demo/
This stack overflow has a few more solutions depending on your set up. http://stackoverflow.com/questions/10732690/offsetting-an-html-anchor-to-adjust-for-fixed-header
Colin Marshall
32,861 PointsThanks Kevin! I went with this jQuery solution, which looks pretty nice to me.
$("body").on("click", "a", function() {
fromTop = 150;
href = $(this).attr("href");
// If href is set, points to an Anchor, and the Anchor is not simply #
if(href && href.indexOf("#") != -1 && href.indexOf("#") != href.length - 1) {
href = href.substring(href.indexOf("#"));
if($(href).length > 0) { // If element exists
$('html, body').animate({scrollTop: $(href).offset().top - fromTop}, 400);
return false;
}
}
});