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 trialZachary Danz
Front End Web Development Techdegree Graduate 15,024 PointsCan I make it so clicking a nav item takes me about 20 pixels higher than the linked ID, accounting for the nav bar?
When I click on any link in the nav bar, the relevant Headings are always covered up by the nav bar. Is there any way to adjust the offset of where it takes you?
Thank you in advance (:
1 Answer
Kosha Burnett
3,340 PointsThere's a CSS solution that involves a negative margin so it's not ideal on Firefox. The best solution that I've encountered is this one:
function offsetAnchor() {
if (location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 20);
}
}
// Captures click events of all a elements with href starting with #
$('a[href*=#]:not([href=#])').click(function() {
// Click events are captured before hash changes. Timeout
// causes offsetAnchor to be called after the page jump.
window.setTimeout(function() {
offsetAnchor();
}, 0);
});
// Set the offset when entering page with hash present in the url
window.setTimeout(offsetAnchor, 0);
Where it says window.scrollY - 20, you would adjust the 20 to the number of pixels you want to offset it.
Matt Nickolls
9,895 PointsMatt Nickolls
9,895 PointsHi Kosha
where would you include the above script in the html?
Thanks
Matt
JASON LEE
17,352 PointsJASON LEE
17,352 PointsThis code looks pretty intimidating! No way I could have come up with this on my own.