'data-offset in Bootstrap Scrollspy is not offseting at all

Any value I set to data-offset for scrollspy does not work at all. Here are the relevant html, css, and js code:

HTML

<nav class="navbar navbar-fixed-top navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#"><strong>YOUNG'S PORTFOLIO</strong></a>
    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav navbar-right enlargeItem">
        <li><a href="#aboutBox">ABOUT</a></li>
        <li><a href="#portfolioBox">PORTFOLIO</a></li>
        <li><a href="#contactBox">CONTACT</a></li>
      </ul>
    </div>
  </div>
</nav>

CSS

body {
      background-color: gray;
      padding-top: 110px;
      data-spy='scroll';
      data-target='.navbar';
      data-offset='';
      position: relative;
    }

JS

$('body').scrollspy();

When I scroll to target area where a tag is defined (#aboutBox, #portfolioBox, #contactBox), it does highlight the appropriate list item.

However, it is off a bit, so I wanted to change the offset by changing the data-offset but changing the data-offset does not do anything.

Here is the link to the codepen if someone wants to take a look at the whole thing



Solution 1:[1]

Argh. Couple things wrong with my code.

  1. I was trying to set attributes using CSS! WOW rookie mistake. I need some sleep.
  2. I was using navbar-fixed-top class. So I had to manually offset by 150px.

I applied this to my javascript:

$("body").attr({
    "data-spy": "scroll",
    "data-target": ".navbar"
  }).scrollspy({
    offset: 150
  });

Solution 2:[2]

Come across this thread as i am looking to find out if you can have a negative value on data-offset.

In response to this post You don't have to add any extra JS or CSS for scrollspy to work it's all bundled with bootstrap, you would just add the attributes to the body tag. ref: https://www.w3schools.com/bootstrap4/bootstrap_scrollspy.asp

<body data-spy="scroll" data-target=".navbar" data-offset="150">

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Danii
Solution 2