The data-offset attribute in Bootstrap Scrollspy seems to have no effect on the offset

My attempts to adjust the data-offset for scrollspy seem to have no effect. Below, you can find the relevant snippets of HTML, CSS, and JS:

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();

Although the scrollspy functionality correctly highlights list items when scrolling to designated areas (#aboutBox, #portfolioBox, #contactBox), I found that the alignment was slightly off. Despite my efforts to modify the data-offset attribute, it does not yield any changes.

If you would like to view the complete code, please visit this CodePen link.

Answer №1

Oh no, my code had a couple of mistakes.

  1. I made the silly mistake of trying to set attributes using CSS.
  2. I used the navbar-fixed-top class which meant I had to manually offset by 150px.

To fix this, I updated my JavaScript like so:

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

Answer №2

Just stumbled upon this discussion while trying to figure out if it's possible to have a negative value on data-offset.

Regarding the previous message, there is no need to include any additional JS or CSS for scrollspy to function as Bootstrap already includes everything needed. You simply need to add the specified attributes to the body tag. Reference: https://www.w3schools.com/bootstrap4/bootstrap_scrollspy.asp

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

Answer №3

Check out this code snippet:

$(document).ready(function () {
    offset = 10; // setting extra padding
    nav_top = $("#tsnav"); // grabbing the top navbar height 
    side_nav = $("#cve_info") // selecting the target nav
    nav_height = nav_top.outerHeight() + offset; // calculating the actual distance from the top where content should be fixed 
    
    side_nav.find("a").on('click', function () {
        let $el = $(this);
            id = $el.attr("href");

        $('html, body').scrollTop( $(id).offset().top - nav_height);
        return false;
    })
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React Error: The property 'i' cannot be read as it is undefined

I am encountering an issue with my code: class Albs extends React.Component{ constructor(props){ super(props); this.state = { i: 0, anh: this.props.hinhanh[this.state.i] }; var hinhanh = ["1.png", "2.png", "3.png"]; this. ...

Which One Wins: Render Props or HOC?

As I embark on the journey of learning React from scratch, I am delving deep into the concepts and trying to gain a thorough understanding! Today, my research led me to explore HOCs, Render Props, and discerning the nuances between the two. To gauge their ...

Issue with MUI Data Grid sorting: Data Grid sortComparator function returning undefined

I'm attempting to organize data with nested values in a data grid, but I keep receiving 'undefined' on the sortComparator of Data Grid Columns. Code: Column Data Setup: { headerName: 'Title', field: `${this.props.type} ...

Returning Props in Dynamic Components with Vue 3

Exploring the capabilities of Vue3's Dynamic Component <component>, I am currently working with this setup: Component 1: <template> <div> <h1> Name Input: </h2> <Input :model="props.name" /> ...

Prevent Page Refresh with F5 in Silverlight

Many of the users on my platform are accidentally hitting the F5 key while typing, causing them to lose all their work. I don't want to completely block the ability to refresh the page. I attempted using the following JavaScript solution, however it ...

utilizing a background image with a specific div identifier

I am attempting to achieve the same effect shown in this example: http://www.w3schools.com/cssref/tryit.asp?filename=trycss_background-position I want to set an image as the background of a div using an id. #wrapper { height: 900px; width: 900px; bord ...

Is it considered a bad practice to use the record ID on a <tr> element for an editable row within a table?

I am in the process of using jQuery to create a feature that allows users to edit a HTML table containing category names. Currently, I have successfully populated my table using PHP/MySQL. While researching on jQuery - Edit a table row inline, I came acr ...

Onload, capture page elements, delete them, and then access the original content

I am encountering two DIV elements on my page that I need to capture upon loading the page and preserve their contents until the page is refreshed. The nested DIV element is contained within the other one. After locating these elements initially, I want t ...

Is there a way to apply an indigo color solely to a div using CSS without affecting the entire body?

Can someone help me achieve a result similar to the image shown https://i.sstatic.net/IY1kI.png I've been working on some code, but I haven't been able to get the exact desired outcome. My goal is to make a div indigo and leave the rest of the b ...

Ways to deselect checkboxes with Typescript and Jquery

I have a set of checkboxes all labeled with the same 'types' class. There is a button on my webpage that should be able to toggle between selecting and deselecting all the checkboxes in this group. When checking the boxes, I use the following sc ...

Exploring the Firebug console for JavaScript insights

Currently, I am searching for a method to retrieve the last command that was logged in the firebug console. As an illustration, I could implement something like: console.debug('The most recent request URI is /sweatsocks'); Following that, anot ...

An unexpected error occurred in the Angular unit and integration tests, throwing off the script

I seem to be facing a recurring issue while running unit/integration tests for my Angular project using Karma. The tests have a 50:50 success/failure rate, working fine on my machine but failing consistently on our build server, making the process quite un ...

Problem with using puppeteer to interact with a dropdown menu

I have a project in which I am utilizing puppeteer to create a bot that can automatically check for my college homework assignments. The problem I am encountering is that when the bot tries to click on a dropdown menu, it fails and I receive an error messa ...

Is the value of useState not updating even after setting it in a callback function?

I am facing an issue where the error message is not being added to the error state when an error occurs. The backend sends the error message in JSON format { "error": "error message" }, and even though I can log this error message successfully, the error ...

What is the correct way to show a PHP script as an HTML page following an AJAX call?

Attempting to utilize AJAX to call a php file that will display an html page from my js. Below is the php file in question: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv=& ...

Improving the method for calculating the sum of a property value within an array

I have a similar structure as below: $scope.traveler = [ { description: 'Senior', Amount: 50}, { description: 'Senior', Amount: 50}, { description: 'Adult', Amount: 75}, { de ...

Creating dynamic grid data based on various filter criteria using JavaScript (AngularJS)

In my approach, I have created two JSON data files. If the 'List' value equals A-1, I will retrieve the JSON data specific to that value. Otherwise, I will retrieve all the main data from data.json. My goal is to have 3 other checkbox options un ...

Issue with ng-selected not functioning properly

I am facing an issue where the ng-selected is assigned as true but the option is not being selected. The following is my controller code: .controller("PendingInvoiceCtrl", function($scope, $location, safeApply, dataService) { var userData = dataServi ...

What are the best ways to creatively design HTML content generated using JavaScript?

I am currently using Squarespace 7.1 to create a website that features a randomly generated quote in the footer section. The quote is generated from a JavaScript array when the page loads, reloads, or changes. Despite the code functioning as intended (test ...

Show information in a div when clicked using a data attribute that contains a secondary div with the same data attribute

I have 3 div elements, each containing a unique data attribute: <div class="box"> <div class="item" data-category="#music"> CLICK </div> </div> <div class="box"> <div class="item" data-category="#movies"> CLICK &l ...