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

What is the best way to attach events to buttons using typescript?

Where should I attach events to buttons, input fields, etc.? I want to keep as much JS/jQuery separate from my view as possible. Currently, this is how I approach it: In my view: @Scripts.Render("~/Scripts/Application/Currency/CurrencyExchangeRateCreate ...

What is the best way to populate an array with zeros when there is no data available?

Currently, I am working on a project that involves using chart.js to display monthly profit data up to the current month. The data is retrieved from the server and there are two scenarios to consider: // First scenario data: [ ...

Failure of Outlook 2007, 2010, and 2013 to Recognize Conditional CSS

I am currently working on a design for a responsive email. The layout is functioning well in all email clients tested using Litmus, except for Outlook 07/10/13 due to its challenging word rendering engine versions. To ensure correct display across differen ...

employing a variable within a function that is nested within another function

I'm encountering an issue where I am using a variable within a nested function. After assigning a value to it, I pass it to the parent function. However, when I call the function, nothing is displayed. function checkUserExists(identifier) { let user ...

Tips for resizing a 100% div without displaying vertical scrollbars in the browser

I am facing an issue with a table that has three rows. I have a main #container div with a height of 100%, and inside it is a table with 3 rows. The first and last row contain fixed size content. However, in the second row, there is a #content div with a h ...

There was an error because the variable "items" has not been defined

Having some trouble with an AngularJS service where I am attempting to add an item to an array every 5 seconds. However, I keep encountering the error 'items is not defined' after the first dynamic addition... I've been tinkering with this ...

Utilizing document.write() for displaying markup content

I have an inline SVG stored as a variable on my webpage and I am making some changes to it. How can I display viewText on the page (not the SVG image) with the modifications? What is the best way to make viewText appear on the page? For instance: ...

When completing a form submission, make sure to eliminate the %5B%5D from the

Whenever I submit a form with multiple checkboxes that share the same name, the resulting URL format is as follows: www.example.com/search.php?myvalue%5B%5D=value1&myvalue%5B%5D=value2 Is there a method to eliminate the %5B%5D in the URL and make it m ...

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success or fail message. Instead, I received the entire HTML page code along

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success/fail message. However, I ended up receiving the full HTML page code along with tags. Here is my AngularJS code: $http.post('ajax_Location.php',{ &apos ...

Click on a link to open it in the current tab with customized headers

In my Angular project, I am attempting to open a link by clicking a button that redirects to the specified URL using the following code: window.open(MY_LINK, "_self"); However, in this scenario, I also need to include an access token in the header when t ...

javascript/jquery: ensure Android device displays content in full-screen mode

Currently working on developing a web app specifically for an android device that needs to be displayed in fullscreen mode. I came across the code snippet above on stack overflow, which successfully activates fullscreen mode upon click event. However, I a ...

Is there a way to customize the CSS of a Bootstrap 4 data table

I recently incorporated a library from Bootstrap Datatables into my project. However, I'm having trouble modifying the CSS for the search bar and 'Excel' button. Is there a way for me to customize it with my own CSS? https://i.sstatic.net/x ...

Animation unveiling of text slides

I have been working on designing a unique button for my personal diet app project that involves a sliding text effect when the mouse hovers over it. I'm almost there, but I've encountered a major issue that seems impossible to solve. I want the s ...

The Axios post request is mistakenly sending my data as the key with an empty value instead of sending the entire data object itself

I began by developing the frontend, but now I am looking to create the backend in order to establish a connection with a database. const express = require("express"); const bodyParser = require("body-parser"); const cors = require(" ...

What is the best way to pass a websocket instance to Vue.js components and then invoke the send() method on it?

I am attempting to send a message via a web socket to the server when a button is clicked: // HelloApp.vue <template> <div class="hello"> <h1>{{ msg }}</h1> <button v-on:click="sendMessage($event)">Send Message< ...

Storing JSON strings in PHP differs from storing them in JavaScript

Using JavaScript, I can save a cookie using JSON.stringify(), which saves the cookie directly like this: '[{"n":"50fb0d0cc1277d182f000002","q":2},{"n":"50fb0d09c1277d182f000001","q":1},{"n":"50fb0d06c1277d182f000000","q":1}] Now, I am sending this t ...

Custom sized box causing Bootstrap Navbar to be unresponsive

I am having trouble loading the Bootstrap 3 navbar inside a .box class with specific CSS rules: .box { height: 600px; width: 320px; position: relative; border: 2px solid #eee; } Unfortunately, it is not displaying re ...

Update the webpage post a database entry without relying on the setTimeout() function in Javascript

Is there a method to automatically refresh the page after a new entry in the database without relying on Javascript's setTimeout or setInterval functions? Could an AJAX function or a MySQL function accomplish this task instead? Must we continuously ...

Utilize jQuery to toggle classes on and off for anchor elements within list items in an unordered

<ul class="tab_sublinks"> <li><a href="#" class="active">Product Master</a></li> <li style="margin: 0;">|</li> <li><a href="#">Charges Computation Master</a></li> </ul> Ho ...

Angular filter is causing an error message saying "Unable to interpolate," but the filter is functioning as expected

I have implemented the filter below (which I found on StackOverflow) that works perfectly fine on one page. However, when using the same object, it throws an error as shown below: app.filter('dateFormat', function dateFormat($filter){ return f ...