Issue with Bootstrap 4 nav bar where the first nav item is not highlighted and a problem with scrollspy

I have encountered an issue that I need help resolving. My Bootstrap 4 navbar has scrollspy enabled to update as you navigate through the page's sections, and a jQuery function provides smooth scrolling when clicking on navigation links. However, I am facing two problems.

Here is a link to my website: https://codepen.io/tidus198/pen/deWpvX

  1. The first problem is related to the nav bar scrollspy - the default setting does not make the first nav item active. The 'About' section in the navbar is not highlighted when visiting the page or if scrolled to the top. It only becomes active once scrolled down slightly due to the fixed navbar scrolling with the page. How can I ensure the first nav item is active by default?

  2. The second issue occurs when clicking on a nav item; it scrolls past the section title to show content instead of the heading. I managed to fix this using the jQuery offset function to set the correct display. However, now when clicking on 'Contact', the navbar highlights 'Portfolio'. How can I resolve this conflict between the offset correction and the navigation items?

Any assistance would be greatly appreciated.

HTML:

<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>My Portfolio</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
        <link rel="stylesheet" href="css/site.css" type="text/css" />    
    </head>

    <body id = "body">
    <header id="test">
      <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top" >
          <a class="navbar-brand" href="#"><img id="navpic" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Profile Picture" ></a>
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav nav-pills ml-auto" id="homenav">
                <li class="nav-item">
                  <a class="nav-link" href="#test">About <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="#portfolio">Portfolio</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="#contact">Contact</a>
                </li>
              </ul>
          </div>
        </nav>


          <section class="container">

            <div class="jumbotron text-center">
              <div class="row">
                <div class="col-12 col-md-4">
                  <img id="mypic" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Profile Picture" class="img-thumbnail">
                </div>
                <div class="col-12 col-md-8">
                  <h1 class="display-5">Your Name Here</h1>
                  <p class="lead">Front-End Developer and UX/UI designer, with practical experience in project management, branding strategy, and
                    creative direction; devoted to functional programming and information architecture.</p>
                  <hr class="my-4">
                  <p class="small">Web Developer - User Experience Designer - Graphic Artist</p>

                </div>

              </div>

            </div>
          </section>
        </header>

        <main>
          <section id="content-container" class="container">
            <div class="row" id="portfolio">
              <div class="col-12">
                <h2 class="display-5 text-center text-white text-uppercase mb-3">Portfolio</h2>
              </div>
            </div>

            <div class="row">

              <div class="col-lg-6 d-flex align-items-stretch mb-4">
                <div class="card w-100">
                  <img class="card-img-top" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Card image cap">
                  <div class="card-footer text-center">
                    Image One
                  </div>
                </div>
              </div>

              <div class="col-lg-6 d-flex align-items-stretch mb-4">
                <div class="card w-100">
                  <img class="card-img-top" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Card image cap">

                  <div class="card-footer text-center">Image Two</div>
                </div>
              </div>

            </div>

            <div class="row">

              <div class="col-lg-6 d-flex align-items-stretch mb-4">
                <div class="card w-100">
                  <img class="card-img-top" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Card image cap">
                  <div class="card-footer text-center">
                    Image Three
                  </div>
                </div>
              </div>

              <div class="col-lg-6 d-flex align-items-stretch mb-4">
                <div class="card w-100">
                  <img class="card-img-top" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Card image cap">

                  <div class="card-footer text-center">Image Four</div>
                </div>
              </div>

            </div>

            <div class="row">

              <div class="col-lg-6 d-flex align-items-stretch mb-4">
                <div class="card w-100">
                  <img class="card-img-top" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Card image cap">
                  <div class="card-footer text-center">
                    Image Five
                  </div>
                </div>
              </div>

              <div class="col-lg-6 d-flex align-items-stretch mb-4">
                <div class="card w-100">
                  <img class="card-img-top" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Card image cap">

                  <div class="card-footer text-center">Image Six</div>
                </div>
              </div>

            </div>

          </section>
        </main>

        <footer>
          <section class="container">
            <div class="jumbotron mt-2">

              <div class="row">
                <div class="col-12">
                  <h2 class="display-4 text-center pb-2" id="contact">Contact Me</h2>
                </div>
              </div>

              <div class="row">
                <div class="col-12 col-md-8">
                  <form>
                    <div class="form-group">
                      <label for="name">Name</label>
                      <input type="text" class="form-control" id="name" placeholder="Name" required>
                    </div>
                    <div class="form-group">
                      <label for="emailaddr">Email</label>
                      <input type="email" class="form-control" id="emailaddr" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="701e111d15301508111d001c155e131f1d">[email protected]</a>" required>
                    </div>
                    <div class="form-group">
                      <label for="phone">Phone</label>
                      <input type="number" class="form-control" id="phone" placeholder="123-456-7890">
                    </div>
                    <div class="form-group">
                      <label for="textarea">Message</label>
                      <textarea class="form-control" id="textarea" rows="3"></textarea>
                    </div>
                  </form>

                </div>
                <div class="col-12 col-md-4">
                  <p class="lead">Feel free to contact me if you have any additional questions on my portfolio. You can either email me directly
                    at
                    <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45283c2028242c2905283c2028242c296b262a28">[email protected]</a>?subject=Porfolio Question">
                      <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a67736f676b63664a67736f676b636624696567">[email protected]</a></a> or fill out the contact form.
                  </p>

                </div>

              </div>

            </div>

          </section>
        </footer>

      </div>
      <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
      <script src="js/app.js" type="text/javascript"></script>

    </body>
</html>

CSS:

blockquote {
  border-left: none;
}

#body {
    background-color: #464646;
    padding-top: 65px; 
    position: relative;
}

#mypic {
  width: 200px;
  height: 200px;
  border-radius: 50%;
}

#navpic {
  width: 40px;
  height: 40px;

}

.jumbotron #contact {
  margin-top: -50px;
}

form label {
  font-weight: bold;
}

#homenav > li > a:hover{
    background-color:grey;
    box-shadow: 0px 2px 2px 1px rgba(0, 0, 0, 0.1);
  } 

#about{
  position: relative;
  top: 1px;
}

JS:

$(document).ready(function (){
    $('body').scrollspy({ target: '.navbar' });

    $('.nav-link').on('click', function(){
        var clickedItem = $(this).attr('href');
       $('html, body').animate({
            scrollTop: $(clickedItem).offset().top - 80
       }, 1500);
    });

});

Answer №1

After making a few adjustments, everything seems to be in order. Take a look at my version here: https://codepen.io/mdlanglais/pen/OZmWNV

HTML

<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>My Portfolio</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
    <link rel="stylesheet" href="css/site.css" type="text/css" />    
</head>

<body id = "body" data-spy="scroll" data-target="#navbarNav">
<header id="test">
  <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top" >
      <a class="navbar-brand" href="#"><img id="navpic" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Profile Picture" ></a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav nav-pills ml-auto" id="homenav">
            <li class="nav-item">
              <a class="nav-link active" href="#test">About <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#portfolio">Portfolio</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#contact">Contact</a>
            </li>
          </ul>
      </div>
    </nav>


      <section class="container">

        <div class="jumbotron text-center">
          <div class="row">
            <div class="col-12 col-md-4">
              <img id="mypic" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Profile Picture" class="img-thumbnail">
            </div>
            <div class="col-12 col-md-8">
              <h1 class="display-5">Your Name Here</h1>
              <p class="lead">Front-End Developer and UX/UI designer, with practical experience in project management, branding strategy, and
                creative direction; devoted to functional programming and information architecture.</p>
              <hr class="my-4">
              <p class="small">Web Developer - User Experience Designer - Graphic Artist</p>

            </div>

          </div>

        </div>
      </section>
    </header>

    <main>
      <section id="content-container" class="container">
        <div class="row" id="portfolio">
          <div class="col-12">
            <h2 class="display-5 text-center text-white text-uppercase mb-3">Portfolio</h2>
          </div>
        </div>

        <div class="row">

          <div class="col-lg-6 d-flex align-items-stretch mb-4">
            <div class="card w-100">
              <img class="card-img-top" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Card image cap">
              <div class="card-footer text-center">
                Image One
              </div>
            </div>
          </div>

          <div class="col-lg-6 d-flex align-items-stretch mb-4">
            <div class="card w-100">
              <img class="card-img-top" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Card image cap">

              <div class="card-footer text-center">Image Two</div>
            </div>
          </div>

        </div>

        <div class="row">

          <div class="col-lg-6 d-flex align-items-stretch mb-4">
            <div class="card w-100">
              <img class="card-img-top" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Card image cap">
              <div class="card-footer text-center">
                Image Three
              </div>
            </div>
          </div>

          <div class="col-lg-6 d-flex align-items-stretch mb-4">
            <div class="card w-100">
              <img class="card-img-top" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Card image cap">

              <div class="card-footer text-center">Image Four</div>
            </div>
          </div>

        </div>

        <div class="row">

          <div class="col-lg-6 d-flex align-items-stretch mb-4">
            <div class="card w-100">
              <img class="card-img-top" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Card image cap">
              <div class="card-footer text-center">
                Image Five
              </div>
            </div>
          </div>

          <div class="col-lg-6 d-flex align-items-stretch mb-4">
            <div class="card w-100">
              <img class="card-img-top" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="Card image cap">

              <div class="card-footer text-center">Image Six</div>
            </div>
          </div>

        </div>

      </section>
    </main>

    <footer>
      <section class="container">
        <div class="jumbotron mt-2">

          <div class="row">
            <div class="col-12">
              <h2 class="display-4 text-center pb-2" id="contact">Contact Me</h2>
            </div>
          </div>

          <div class="row">
            <div class="col-12 col-md-8">
              <form>
                <div class="form-group">
                  <label for="name">Name</label>
                  <input type="text" class="form-control" id="name" placeholder="Name" required>
                </div>
                <div class="form-group">
                  <label for="emailaddr">Email</label>
                  <input type="email" class="form-control" id="emailaddr" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3ada2aea683a6bba2aeb3afa6eda0acae">[email protected]</a>" required>
                </div>
                <div class="form-group">
                  <label for="phone">Phone</label>
                  <input type="number" class="form-control" id="phone" placeholder="123-456-7890">
                </div>
                <div class="form-group">
                  <label for="textarea">Message</label>
                  <textarea class="form-control" id="textarea" rows="3"></textarea>
                </div>
              </form>

            </div>
            <div class="col-12 col-md-4">
              <p class="lead">Feel free to contact me if you have any additional questions on my portfolio. You can either email me directly
                at
                <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3beaab6beb2babf93beaab6beb2babffdb0bcbe">[email protected]</a>?subject=Porfolio Question">
                  <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d302438303c34311d302438303c3431733e3230">[email protected]</a></a> or fill out the contact form.
              </p>

            </div>

          </div>

        </div>

      </section>
    </footer>

  </div>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
  <script src="js/app.js" type="text/javascript"></script>

</body>

CSS

blockquote {
  border-left: none;
}

#body {
    background-color: #464646;
    padding-top: 0px; 
    position: relative;
}

#mypic {
  width: 200px;
  height: 200px;
  border-radius: 50%;
}

#navpic {
  width: 40px;
  height: 40px;

}

.jumbotron #contact {
  margin-top: -50px;
}

form label {
  font-weight: bold;
}

#homenav > li > a:hover{
    background-color:grey;
    box-shadow: 0px 2px 2px 1px rgba(0, 0, 0, 0.1);
  }

#test {
  padding-top: 95px;
}

#about{
  position: relative;
  top: 1px;
}

JS

$(document).ready(function (){
  $('body').scrollspy({ target: '.navbar' });

  $('.nav-link').on('click', function(){
    var clickedItem = $(this).attr('href');
    $('html, body').animate({
        scrollTop: $(clickedItem).offset().top
    }, 1500);
  });
});

I made some slight tweaks such as setting the About link as active initially, adjusting positioning values in the JavaScript, and modifying padding styles. There may be alternative ways to achieve similar results.

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

What is the best way to implement KaTeX in a React application?

Can someone help explain how KaTex can be incorporated into a React application? Despite reviewing the documentation on NPM, I am still having trouble understanding. I am specifically confused on how katex.render and katex.renderToString functions can be ...

custom vertical tab label text not aligning to the right in material-ui with textAlign

I am struggling with customizing the tabs in material-ui to display them vertically. I also want the text labels of these tabs to align to the right for a more cohesive look. Despite trying various styling options, I have not been successful in achieving t ...

Transferring parameters from a jQuery post function to a controller

I am facing an issue where the controller is not receiving the "name" parameter that I want to send as a parameter. $(document).ready(function () { $("#btn1").click(function () { var name = $("#search").val(); //name = "ali"; alert(name); ...

What is the best way to retrieve an array of objects from Firebase?

I am looking to retrieve an array of objects containing sources from Firebase, organized by category. The structure of my Firebase data is as follows: view image here Each authenticated user has their own array of sources with security rules for the datab ...

JavaScript Arrays are not functioning properly within the Poo constructor

Attempting to insert data into a JavaScript Array within my constructor has resulted in this error message: TypeError: this.listeetudiant is undefined This is my constructor: function Cours(){ */the array causing trouble: */ this.listeetudiant=[]; */ ...

What is the best method to extract jQuery JSON request attributes in a servlet?

I am currently working with the following JavaScript code: var data = {message:"Hi"} var sendJson = function (){ alert(data); $.ajax({ url:"./jsonTest", data: data, contentType:"application/json", type:"post", ...

Tips for updating the background color of a select option

I'm looking to customize the background color of select options in my Bootstrap 4 form. Can anyone provide guidance on how to achieve this? `` <div class="form-group "> <select class="form-control > <option va ...

Pass the ID parameter to the AJAX jQuery function

Hi everyone! I have a search input field where the value is sent to an AJAX jQuery function successfully, and the result is displayed in a div. Now, I want to know if it's possible to send the ID value from that div to another AJAX jQuery function. I& ...

Is there a way to send a Map object to a script file using EJS?

I am facing an issue with passing a Map object to my client-side code. I have successfully used EJS and JSON.stringify(...) in the past for arrays, but it doesn't seem to work for Maps. When I try to console.log(myMap.keys()), I receive the following ...

Is there a way for me to incorporate a feature where the user has the option to choose the number of passwords they would

I created a password generator for my company and now I want to implement the feature where the user can choose how many passwords they want. My attempt at using str_repeat ($output , $password_amount ) resulted in duplicate passwords being generated, mak ...

Convert the date and time of "2018-03-31T05:37:57.000Z" to a

I need help converting the universal time 2018-03-31T05:37:57.000Z to a timestamp in the form of 1520919620673. Can someone please provide guidance on how I can achieve this conversion? ...

Verify whether a certain key exists within the gun.js file

Suppose I need to verify whether a specific entry exists in the database before adding it. I attempted the following: gun.get('demograph').once((data, key) => { console.log("realtime updates 1:", data); }); However, I only receive ...

Switching the phone formatting from JavaScript to TypeScript

Below is the JavaScript code that I am attempting to convert to TypeScript: /** * @param {string} value The value to be formatted into a phone number * @returns {string} */ export const formatPhoneString = (value) => { const areaCode = value.substr(0 ...

Is there a way to display two cards side by side in mobile view?

On a desktop view, 2 cards are displayed in a row. I would like them to also appear in a row on mobile view. I tried using col-sm-4 but it's not working. How can I get the cards to display in a row on mobile view so that I can see both the product pho ...

Seamless Axios operations even without internet connection in Vue.js

In my Nativescript Vue.js application, there is a functionality where the user clicks on login, Axios makes a call to an endpoint to fetch a token. However, I noticed that when the emulator phone is offline, the Axios call still goes through and the &apos ...

Displaying items using the flex property can cause the top resize feature to be unreachable

My issue revolves around the display of input errors, which are causing the top section to become inaccessible. I am looking for a solution that will align the content both vertically and horizontally in the center. The challenge arises when the card conta ...

Guide to generating interactive material-ui components within a react application?

I am facing a challenge in creating a dynamic mui grid element triggered by a button click in a React component. When attempting to create let newGrid = document.createElement('Grid'), it does not behave the same way as a regular div creation. D ...

Unable to find JSON data using the Javascript Kafka Magic Tool, as no results are being

In JSON format, I have a message that contains various details. My goal is to utilize Javascript search functionality to identify if the EmailAddress matches the specific value I am looking for within hundreds of similar messages: "Message": { ...

What could be causing the CastError: Cast to ObjectId failed in my code?

Whenever I try to access a specific route in my project, the following error is returned: Server running on PORT: 7000 /user/new CastError: Cast to ObjectId failed for value "favicon.ico" (type string) at path "_id" for model "User" at model.Query.exe ...

Unable to choose anything beyond the initial <td> tag containing dynamic content

Struggling to implement an onclick delete function on dynamically selected elements, but consistently encountering the issue of only selecting the first element each time. // Function for deleting entries $("#timesheet").on('click', &ap ...