Forbes magazine logo Ranked Best Coding Bootcamps 2023

How to add offset to bootstrap scrollspy for nav bar links

Altcademy Team wrote on 7 February 2018

Hi you all! I am building my portfolio page but I have a problem. When I click on a navbar link, it scrolls down and overlaps the title of each section. I tried the following workaround

$(document).ready(function(){ $('a[href^="#"]').click(function(e) { e.preventDefault(); var target = this.hash, $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top-80 }, 300, 'swing', function() { window.location.hash = target; }); }); });

This works but it is not okay for me, since when I use the navigation bar, active section is not showing properly.
Does anyone know a different solution in order to solve my problem? You can see my code here https://codepen.io/crisBarreiro/pen/oLQPWR Thank you in advance

Original question by CrisBarreiro

To fix the nav link not showing as active when the section is at the bottom of the nav bar, you can add an offset to the scrollSpy like this:
<body data-spy="scroll" data-target="#myScrollspy" data-offset="80"> ... </body>

You can find this information on the Bootstrap doc https://getbootstrap.com/javascript/#scrollspy-options Here is the working codepen

CrisBarreiro: That solved my problem, thank you!

Trusted by

Students and instructors from world-class organizations

Imperial College London
Carnegie Mellon University
City University of Hong Kong
Hack Reactor
Cisco Meraki
University of Oxford
Swift
Bazaarvoice
Waterloo
Uber
AtlanTech
Tumblr
Boston College
Bombardier Aerospace
University of St. Andrews
New York University
Minerva Schools at KGI
Merrill Lynch
Riot Games
JP Morgan
Morgan Stanley
Advanced Placement®
Google
KPMG
The University of Hong Kong
University of Toronto
SCMP
Moat
Zynga
Hello Toby
Deloitte
Goldman Sachs
Yahoo
HSBC
General Assembly
Tesla
McGill University
Microsoft

Join the upcoming Cohort #96

Enroll for December 2nd, 2024