Navigational highlighting of current page section on a one-page website

I'm struggling with adding a navigation bar feature that will highlight the current section being viewed on my website. All I want is for the currently viewed section to appear bold in the navigation bar.

Check out the codepen link:

HTML

  <nav id="nav-wrap">
    <ul>
      <li class="current"><a class="page" href="#home">Home</a></li>
      <li><a class="page" href="#about">About</a></li>
      <li><a class="page" href="#portfolio">Portfolio</a></li>
      <li><a class="page" href="#scrapbook">Scrapbook</a></li>
      <li><a class="page" href="#contact">Contact</a></li>
    </ul>
  </nav>

  <div class="header-content">
    <img id="logo" src="img/logo.png" alt="logo" height="200px" width="200px">
    <h3>Joseph Cooper</h3>
    <h3>Graphic Designer</h3>
    <p> 10.03.97 </p>
  </div>

<a href="#about"><img id ="down" src="img/down.png" height="42px" width="42px"></a>

Answer №1

After some modifications, I managed to adjust the formatting of the navigation links on my webpage. One line of code was added to remove the bold style from all href elements in the navigation, while another line was included to apply bold styling to the href that is clicked. You can see the updated code on CodePen: http://codepen.io/anon/pen/doaRjy

function smoothScroll(duration) {
    $('a[href^="#"]').on('click', function(event) {        
        var target = $( $(this).attr('href') );

        $("#nav-wrap a").css('font-weight','normal')/*this line removes bold from all href*/
        $(this).css('font-weight','bold')/*this line adds bold to clicked href*/

        if(target.length) {
            event.preventDefault();
            $('html, body').animate({
                scrollTop: target.offset().top
            }, duration);
        }
    });
}

Answer №2

I attempted to resolve this issue by utilizing jQuery's offset().top method and comparing it with the window's scrollTop value.

var $window = $(window),
  homeLink = $("a[href='#home']"),
  aboutLink = $("a[href='#about']"),
  portfolioLink = $("a[href='#portfolio']");

$window.on("scroll", function(e) {

  if ($window.scrollTop() < $("#about").offset().top) {

    $("#nav-wrap").find("a").css("font-weight", 400);
    homeLink.css("font-weight", 900);

  } else if ($window.scrollTop() > $("#about").offset().top && $window.scrollTop() < $("#portfolio").offset().top) {

    $("#nav-wrap").find("a").css("font-weight", 400);
    aboutLink.css("font-weight", 900);

  }

});

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

Retrieve a JSON array using an HTTP Get request in JavaScript (with jQuery)

I’ve been experimenting with various code snippets in an attempt to reach my objective, but so far I haven’t found a solution. Objective: My goal is to retrieve a JSON array of objects from a specific web URL using the GET method. This task needs to b ...

During operational hours, an Ajax request may cause interruptions to the website's functionality

Having an issue with a large ajax request: I am querying a PHP file that makes some cURL requests, taking 15-20 seconds to complete and then returning JSON on my webpage. It's a standard ajax request, but I found a strange bug. While the ajax query i ...

Mystery of the Unresponsive MD Ripple Button

While working on creating a CSS button, I wanted to incorporate the Material Design ripple or wave effect into it. I came across a simple script on codepen that works well by adding the class "ripple" to various elements such as divs, buttons, images, and ...

What is the solution for fixing the Typescript error in formik onSubmit?

I encountered an error while using the onSubmit prop of Formik: The type '(values: { email: string; password: string; }) => { type: string; payload: { email: string | null; password: string | null; }; }' is not compatible with the type '(( ...

Tips for dividing echo output from PHP into two separate divs using jQuery AJAX

I am trying to display two different echoes from PHP in separate divs within my AJAX success function. $.ajax({ url: 'counter.php', type: 'POST', data: { some_data:some_data ...

Guide for redirecting puppeteers' attention to a new pop-up interface

Currently, I am utilizing Puppeteer to carry out a test on a website. Upon clicking a button, a new popup browser window emerges displaying a report. Inside this new window lies data that I wish to extract. Is there a method for Puppeteer to switch its foc ...

JavaScript is sending a variable to a .php file, which then returns data based on the variable. The information is displayed using JavaScript and AJAX, along with triggers set using the bind('input', function

Currently, I am attempting to create a form that automatically populates some input fields when there is a change. However, I am struggling to understand how to send the #url field to my PHP script. Any insights or suggestions would be greatly appreciated. ...

Upon clicking the checkbox, only the ul tag will be displayed on the screen

It's puzzling to me that when I click on the checkbox, only the ul tag with id=menu is visible on the screen, not id=social. I need to ensure display:block is set for every ul tag. .show-menu { display:block; } #menu{ float:left; } #social{ ...

Challenge with JavaScript personalized library

No matter how many times I review my code, I find myself perplexed. Despite my efforts to create a custom library of functions from scratch (shoutout to stackoverflow for guiding me on that), the results are leaving me puzzled. A javascript file is suppose ...

Modify the color of the active class in Bootstrap

I am trying to modify the color of the active class in my HTML code as I create a nav sidebar. Here is the snippet from my code: <div class="col-sm-2"> <ul class="nav nav-pills nav-stacked nav-static"> <!--stacked for vertic ...

How can you determine if multiple checkboxes have been checked with "if" statements following a button click?

I am looking to display a message after clicking a button if one or more checkboxes are checked. I would prefer using Jquery for this functionality. Any help on achieving this would be highly appreciated. $(function() { $(".btn").click(function() { ...

Turn off the scroll function while loading a webpage

Here is the script for my preloader: $(window).load(function() { $("#loading").fadeOut(1000); I want to prevent scrolling while the "loading" is still visible, and then enable it again after the fade out completes. ...

An error occured upon loading FullCalendar: Uncaught TypeError - Unable to read property 'push' as it is undefined

First of all, thank you for your assistance. I've been trying to load FullCalendar (https://fullcalendar.io/) on my development environments but it doesn't seem to be working. When I check the console in Chrome, it shows me the following error m ...

Troubleshooting: jQuery AJAX not Invoking C# Method in ASP.NET MVC Application

I am attempting to initiate a call to the controller from the views using jQuery ajax, however, it seems like the controller is not being called. The goal is to pass the token value obtained on the registration page to the controller in order to utilize it ...

Share JSON data across functions by calling a function

I am currently working on a project where I need to load JSON using a JavaScript function and then make the loaded JSON objects accessible to other functions in the same namespace. However, I have encountered some difficulties in achieving this. Even after ...

The placement of footers remains consistent

Struggling with the placement of my footer on a website I'm designing. The footer should be at the bottom of the page with a set percentage margin, but it's not working as expected. Here is a link to My website Reviewing the footer CSS: .foote ...

Why does my express POST request result in an empty req.body in Node.js?

After confirming that my data is being passed correctly and the db connection is successful, I am facing an issue with my ajax request. Even though the success callback returns the id, my data seems to not be passing through properly. When attempting to a ...

Adjusting the width of titles in a CSS menu upon hover

I am currently creating a basic CSS menu. However, I am facing an issue where selecting a menu title in the menu bar causes the width of the title to extend to match the width of the associated menu, which is not my desired outcome (the title's width ...

Associating checkbox options with an array that is void of elements

I have a series of arrays linked to checkboxes and I am trying to create a unique array based on the selected checkbox values. Here is an example of the HTML structure: <input type="checkbox" value="value1">Value 1 <input type="checkbox" value=" ...

How can I retrieve data submitted in a POST request on my Node.js server

I'm having trouble sending form data to a node/express server using AJAX. After submitting, I keep getting redirected to a 'Cannot POST /' page. Although I can log the request object on the server side, the data from the form is missing. Wha ...