What is the best way to highlight Navbar links when reaching a specific section?

When designing my website, I encountered an issue with the active navigation link style. It successfully changes when clicked and scrolled to the section, but does not update when the user scrolls away. How can I make the active style update on user scroll?

HTML code

      <nav id="topNav" class="navbar navbar-expand-lg navbar-light ">
        <a class="navbar-brand" href="#landing"><img id="brandLogo" src="project-images/portfolio logo2.png" alt=""></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 ml-auto">
            <li class="nav-item active">
              <a class="nav-link" href="#about">About <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#skills">Skills</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#projects">Projects</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#contact">Contact</a>
            </li>
           
          </ul>
        </div>
      </nav>

CSS code

.navbar {
        position: fixed;
        width: 100%;
        height: 90px;
        z-index: 1000;
        margin: 0;
        padding: 1.5rem 8rem !important;
        /* background: #262626; */
        background: transparent;
        transition: 0.5s ease-out;
        /* background: transparent !important; */
    }

    .navbar .navbar-nav a{
        background: -webkit-linear-gradient(#e6e6ff, #6666ff);
       -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-size: 20px !important;
        margin: 10px;
        padding: 10px 30px;
        font-family: 'Ubuntu', sans-serif;
        transition: 0.7s;
    }

    .navbar .navbar-nav a:hover {
        background: -webkit-linear-gradient(#e6e6ff, #fff);
        -webkit-background-clip: text;
         -webkit-text-fill-color: transparent;
        /* color: #1b2735 !important;
        border-radius: 30px; */
    }

    .nav-item{
        background: transparent !important;
    }
   
    
    #topNav.scroll-menu {
        background: #090a0f;
        border-bottom: 0.5px solid #b3b3ff;
        height: 90px;
        box-shadow: 0 4px 5px rgba(0, 0, 0, 0.2);
    }


    #topNav.scroll-menu a {
      color: #0f1f3d !important;
      transition: 0.6s ease-in-out;
    }
    
 #topNav.scroll-menu ul li.active a{

    border: 1px solid #6666ff;
    border-bottom: #6666ff;
    border-radius: 30px;
    
        
    } 
    
    #topNav.scroll-menu a:hover{
        color: #fff;
            
    }

JavaScript code

window.addEventListener("scroll", function(){
    let topNav = document.getElementById("topNav");

    if(window.pageYOffset >  750) {
        topNav.classList.add("scroll-menu");
    } else {
        topNav.classList.remove("scroll-menu")
    }

});


$(window).scroll(function(){
    let position = $(this).scrollTop();

    $('.section').each(function(){
        let target = $(this).offset().top;
        let id = $(this).attr('id');

        if(position >= target) {
            $('#topNav > ul > li > a').removeClass('active');
                $('#topNav > ul > li > a [href=#' + id + ']').addClass('active') 
        } 
    })



});

Answer №1

Being new to this area, I'm unsure if my approach is correct. However, I believe it might be helpful as I referenced this code when facing a similar situation. CodePen Link
Alternatively, you can also refer to this JSFiddle link

<div class="m1 menu">
    <div id="menu-center">
        <ul>
            <li><a class="active" href="#home">Home</a>

            </li>
            <li><a href="#portfolio">Portfolio</a>

            </li>
            <li><a href="#about">About</a>

            </li>
            <li><a href="#contact">Contact</a>

            </li>
        </ul>
    </div>
</div>
<div id="home"></div>
<div id="portfolio"></div>
<div id="about"></div>
<div id="contact"></div>

.menu {
width:

 100%;
    height: 75px;
    background-color: rgba(0, 0, 0, 1);
    position: fixed;
    background-color:rgba(4, 180, 49, 0.6);
    -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    transition: all 0.3s ease;
}
.light-menu {
    width: 100%;
    height: 75px;
    background-color: rgba(255, 255, 255, 1);
    position: fixed;
    background-color:rgba(4, 180, 49, 0.6);
    -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    transition: all 0.3s ease;
}
#menu-center {
    width: 980px;
    height: 75px;
    margin: 0 auto;
}
#menu-center ul {
    margin: 15px 0 0 0;
}
#menu-center ul li {
    list-style: none;
    margin: 0 30px 0 0;
    display: inline;
}
.active {
    font-family:'Droid Sans', serif;
    font-size: 14px;
    color: #fff;
    text-decoration: none;
    line-height: 50px;
}

$(document).ready(function () {
    $(document).on("scroll", onScroll);
    
    //smoothscroll
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();
        $(document).off("scroll");
        
        $('a').each(function () {
            $(this).removeClass('active');
        })
        $(this).addClass('active');
      
        var target = this.hash,
            menu = target;
        $target = $(target);
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top+2
        }, 500, 'swing', function () {
            window.location.hash = target;
            $(document).on("scroll", onScroll);
        });
    });
});

function onScroll(event){
    var scrollPos = $(document).scrollTop();
    $('#menu-center a').each(function () {
        var currLink = $(this);
        var refElement = $(currLink.attr("href"));
        if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
            $('#menu-center ul li a').removeClass("active");
            currLink.addClass("active");
        }
        else{**strong text**
            currLink.removeClass("active");
        }
    });
}

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

Issue with IE11: the selected list is not displayed when using the <s:optiontransferselect> tag

When moving groups from left to right in the s:optiontransferselect for selectedGrps and unselectedGrps, the SelectedGroups list is showing as null on form submission in IE11. However, in Chrome and Mozilla, it functions correctly. Any advice would be grea ...

Querying a collection with a bulk request using Mongoose Cursor

My current challenge involves working with rxJS and handling bulk HTTP requests from a database containing over 1 million documents. The code I have is relatively simple. I am pushing all the documents from the collection into an array called "allPlayers" ...

AngularJS: Updated URL but no content displayed on the page

I have separate modules for my login page, which uses the loginApp module, and my home page, which utilizes the myApp module. Upon submitting on the login page, I aim to direct users to home.html. Within my index.html (login page), the script is as follow ...

The custom component I created seems to be unaffected by the inline styles in React

Having an issue with a custom component where I am trying to add margin-top in one of my uses. I attempted using <MyComponent style={{ marginTop: '10px' }}> and also const myStyle = { marginTop: '10px' }; `<MyComponent style= ...

Mocking default constructor in Jest

Here is some code I'm struggling with: import Web3 from 'web3'; jest.mock('web3', ()=>{ return jest.fn().mockImplementation(()=>'Hello, world!') }); describe('app', ()=>{ test('mock web3& ...

The route parameters seem to be malfunctioning when using the Google Maps Directions API

Currently, I am attempting to transfer the latitude and longitude of a location from one HTML file to another using the $routeParams feature. In the second HTML file, I utilized the Google Maps directions API to display the directions from the source lati ...

Chrome leak when rounded border in `overflow:hidden` parent is exceeded

Even with a rounded parent element, the hidden part of a child element continues to appear in Chrome: In Internet Explorer, adding the CSS property z-index to the parent element can solve this issue. However, this solution does not work in Chrome. #con ...

Why React's setState is only returning the last item when a list is saved to a variable

Being a newcomer to React, I am currently working on a small project that involves using the GitHub API to perform a search and display the results on the screen via AJAX. Right now, I am utilizing a for loop to iterate through the response data, saving it ...

"Enhance User Experience with Autoplay.js for Interactive Content and Sound Effects

I'm trying to get both the animation and audio to start playing automatically when the page loads. Currently, the animation pauses when clicked, but I want it to load along with the audio playback. I attempted to use var playing=true; to enable autop ...

Using the setMovementMethod (Scrolling) function in a textView can cause conflicts with the scaleGestureDetector (zooming) feature

Thank you for taking the time to read this. I have a textView that can be pinch-zoomed, and by adding "textview.setMovementMethod(new ScrollingMovementMethod());" to my code, I am able to scroll the zoomed textview as well, which is exactly what I need. ...

Declare React component as a variable

I'm facing a simple issue that I need to solve. After creating a React app using npx create-react-app, I designed a Map component which I integrated into my view with the following code: class App extends Component { render() { return ( ...

How can I retrieve information from a MySQL Table and display it on an HTML page?

Seeking Solution, I've experimented with Node.JS, but unfortunately, it does not seem suitable for webpage functionality. Online resources mostly discuss displaying HTML through Node.JS without mentioning SQL integration. My experience with PHP is l ...

Adding auth0 authentication to a Next.js 13 application: A step-by-step guide

Currently, I am using a nextjs 12 application and set up auth0 as my authentication provider by following the guidelines provided here: https://auth0.com/docs/quickstart/webapp/nextjs/interactive. However, I am now looking to upgrade my application to next ...

The display of options in React Bootstrap typeahead is not functioning properly

When I try to implement React Bootstrap Typeahead, the options do not appear in the Typeahead component upon page load. Here is a snippet of my code: const React = require('react'); ... (code continues) The options are generated as follows: [ ...

The removal of anonymous function callbacks in jQuery.Callbacks is being discussed

Once a callback function is added to $.Callbacks(), it can be removed as shown below: var callbacks = $.Callbacks(), foo = function() { console.log('Hello world') }; callbacks.add(foo); callbacks.fire(); // logs 'Hello world' call ...

Steps to retrieve the content of a div element and store it in a variable in Ionic 4

I am currently using Ionic 4 and need to extract the text from within my div. Below is the code snippet from home.page.html: <ion-item> <div id="Target" class="editable" [innerHtml]="resume" contenteditable> <p>Lorem ipsum d ...

Showing PDF files using Binary Data in JQuery

Binary data is new to me, but I'm working with Laravel and have a PDF file located at storage/filename.pdf. When I retrieve the file as binary data from the backend, the response is also in binary form. https://i.sstatic.net/7FU18.jpg My goal is to ...

Create a Boxplot chart using Chart.js that dynamically adjusts the minimum and maximum values to allow for additional space on either

I am utilizing chartjs v2.9 for creating a boxplot and my code structure is as follows: function generateRandomValues(count, minimum, maximum) { const difference = maximum - minimum; return Array.from({length: count}).map(() => Math.random() * ...

Is the width set to fill the entire partial screen?

I'm facing a dilemma: I want the darkest-gray bar at the bottom right (visible after running the code below) to stretch as far as the browser window allows without encroaching on the light-gray section on the left. Here's the code snippet: <d ...

adjusting array based on screen size fluctuations

Imagine having two arrays of images named landscape_images[] and portrait_images[]. One is for the landscape view and the other for the portrait view. When the screen width is in landscape mode, the wide resolution images will be displayed on the body. C ...