Illuminate the current page

I have been working on a website with around 20 pages that all have a side navigation bar. To make it easier to manage, I decided to centralize the links in a JavaScript (JS) file and include it on each HTML page. This way, any changes can be made quickly and uniformly across all pages.

One issue I'm facing is how to highlight the active page on the side navigation bar. Below is the JS code I am using (W3CSS is utilized for styling):

document.write('<h4>Services:</h4>\
<div class="w3-bar-block w3-light-grey">\
    <a href="/page/7/alternative-dispute-resolution" class="w3-bar-item w3-button">Alternative Dispute Resolution</a>\
    <a href="/page/8/appellate-practice" class="w3-bar-item w3-button">Appellate Practice</a>\
    // More links...
    <a href="/page/27/workmens-compensation" class="w3-bar-item w3-button">Workmens Compensation</a>\
</div>')

HTML:

<div class="w3-display-container w3-content w3-white" id="home" style="min-width:100%;">
    <div class="w3-content w3-white">
        <div class="w3-row">
            <div class="w3-twothird w3-margin-top" style="font-size: 18px; text-align: justify; padding-left: 5%; padding-right: 5%;">
                <p>content</p>
            </div>
            <div class="w3-third w3-padding">
                <script src="services.js"></script>
            </div>

        </div>
    </div>
</div>

Answer №1

Initially, it's crucial to note that utilizing a synchronous JavaScript file for managing navigation is typically deemed as unwise. In cases where a user accesses your site with JavaScript disabled, the navigation menu wouldn't be visible. A more effective approach would involve integrating a shared navigation template using PHP or another server-side language.

If you absolutely have a requirement to handle it client-side in this fashion, the optimal solution would be to inspect each link within the navigation to determine if it corresponds to location.pathname and then toggle a class accordingly.

// gather all navigation links via a query:
var navLinks = document.querySelectorAll('.w3-bar-block.w3-light-grey a.w3-bar-item.w3-button');

// iterate through the navigation links:
for (var i = 0; i < navLinks.length; i++) {
    var link = navLinks[i];
    // verify whether link path matches current path and apply a class
    if (link.pathname === location.pathname) {
        link.classList.add('w3-green');
    }
}

In an ideal scenario, it would be highly recommended to make the entire navigation system dynamic. Here's a sample implementation:

(function() {
    // store the list of sidebar links as an array of objects:
    var links = [
        {
            url: '/page/7/alternative-dispute-resolution',
            title: 'Alternative Dispute Resolution'
        },
        {
            url: '/page/8/appellate-practice',
            title: 'Appellate Practice'
        },
        {
            url: '/page/9/aviation-law',
            title: 'Aviation Law'
        }
    ];

    // begin constructing the HTML:
    var html = '\
    <h4>Services:</h4>\
    <div class="w3-bar-block w3-light-grey">\
    ';

    // loop through all links and generate their HTML:
    links.forEach(function(link) {
        // initial classes for each link:
        var classes = [
            'w3-bar-item',
            'w3-button'
        ];

        // check if this link is active and add a class
        if (link.url === location.pathname) {
            classes.push('w3-green');
        }

        // append HTML for each link:
        html += '<a href="' +
                link.url +
                '" class="' +
                classes.join(' ') +
                '" title="' +
                link.title +
                '">' +
                link.title +
                '</a>';
    });

    // finish off the HTML structure:
    html += '</div>';

    // render it on the page:
    document.write(html);
})();

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

Implementing pagination within a PHP foreach loop

I have a code snippet that fetches films from the database and organizes them by year, then displays each film for that particular year. However, my list of results is becoming too lengthy and I need to implement pagination. I haven't been able to fin ...

Encountering a peculiar problem with the Bootstrap Carousel where the first slide fails to load

There seems to be an issue with the bootstrap carousel where the first slide appears empty initially, but once you slide to the second slide it starts working fine. Navigating through all slides is still possible. <div id="mediakit_carousel" class="car ...

How can we detect line breaks within a selection using JavaScript?

Apologies for the lack of expertise in the content below, as it is being produced by a designer experimenting with coding :D The goal here is to determine the number of lines selected or highlighted by the cursor. When I mention "lines," I mean what is vi ...

Unexpected bug encountered while implementing redux

I received a warning from eslint while working with create-react-app. ./src/components/auth.js Line 24: Unexpected labeled statement no-labels Line 24: 'authenticated:' is defined but never used ...

Can an image map area be identified using radial coordinates?

While I have experience with online Imagemap Generators for rectangular or circular areas in HTML pages, things get a bit tricky when dealing with pie-shaped sections. When trying to make each pie slice a separate area, the image map code generated by thes ...

Convert the div into a string, including only the visible elements

Within the div #allContent, there are multiple nested divs. My goal is to extract the entire content of #allContent as a string, while excluding any invisible divs contained within it. I believe that this task can be achieved using a combination of filter ...

Utilize HighCharts to seamlessly implement multiple series with the help of AJAX requests

I am facing an issue with plotting the performance results on HighCharts using AJAX. The problem lies with the .addSeries API call not functioning correctly. I need assistance in determining if my approach is correct. $(function () { $('#chart3&a ...

What are the steps for showcasing a personalized HTML tag on a web page

I need to capture user input text and display it correctly. This is what I have attempted: <div> <input type="text" ng-model="post.content" /> </div> <div> <div ng-bind-html="post.content| htmlize"></div> < ...

Unexpected error encountered in Angular 2 beta: IE 10 displays 'Potentially unhandled rejection [3] SyntaxError: Expected'

Question regarding Angular 2 Beta: I am starting off with a general overview in the hopes that this issue is already recognized, and I simply overlooked something during my research. Initially, when Angular 2 Beta.0 was released, I managed to run a basic m ...

Python Application Engine - Streamlining Responses from HTML Control Arrays

In my attempt to use App Engine (Python), I am facing a challenge in sending POST values from a variable array of select controls within an HTML form. Each select control is associated with a text describing what the user is rating. For instance, let&apos ...

Calculating the total of fields from populated documents using Mongoose

In my application, I have two main models: User and Track. A User can complete various Tracks and earn points for each one. The schema for the User model looks like this: let userSchema = new mongoose.Schema({ name: {type: String, required: true}, ...

Unable to utilize material tabs in this situation

Discovering the material tabs feature at https://material.angular.io/components/tabs/api#MatTab got me excited to implement it in my project. After adding the suggested import, I encountered an issue where I couldn't find the module "@angular/materia ...

Is the code generated by Webflow.com functional and practical?

Recently, I have discovered the wonders of www.webflow.com for creating an admin layout. It excels in generating a flexbox layout based on my PSD design without requiring me to manually code with Gulp. My plan is to further simplify the process by breaki ...

What is the destination for next() in Express js?

I'm new to javascript, nodejs, and express, and facing confusion with the usage of next(). I am trying to make my code progress to the next router using next(), but it seems to be moving to the next then instead. This is what my code looks like: // ...

Exploring the Realm of Angular Controllers and Services: Embracing Triumphs and

Currently in the process of creating a service layer for an existing web app using Angular. I am transitioning $http requests and data manipulation to custom Angular services. While I have a good understanding of Dependency Injection in services, I am enco ...

Creating a central navigation menu for a website

Currently, I am working on incorporating a menu in the center of a webpage (please note that this is not a top navigation menu). Here is the initial setup: Users are able to click on various menu items to access different content. I have written code fo ...

jQuery UI - Add character right before the final element

My slider is set to range from 10 to 1000 with increments of 20 (10-30-50, etc). I'm looking to add a character before the value on the last step (1000). Currently, it shows values like "560 kr/h" or "400 kr/h", but I want it to display ">1000 kr ...

Using jQuery to populate tables

Here is a table I am working with: <table class="table table-hover"> <thead> <tr> <th>Person</th> <th>Ethereum Address</th> ...

The beforePopState event in next/router is not triggering as expected

Noticing an issue where the beforePopState event is not triggering when I use the back button. This code snippet is part of a hook defined in _app.js according to the documentation. The current version being used is 12.1.5 If anyone has insights on what ...

The first Ajax request is successful, however, the final one is failing to properly pass the data to the designated page

I have encountered an issue with two parsing scripts. The message.php script works without any problems, but when attempting to send data to data.php, the following error occurs: "Notice: Undefined index: userid in D:\xampp\htdocs\metro&b ...