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

The mobile responsive view in Chrome DevTools is displaying incorrect dimensions

Seeking some clarification on an issue I encountered: I recently created a simple webpage and attempted to make an element full width using width: 100vw. However, I observed that on screens smaller than around 300px, the element appeared smaller and not t ...

Tips on sending variables to a PHP script from a JQuery $(document).ready function

I have a chat application in development. I currently have a functioning JQuery code that calls logs.php every second to refresh the chat. $(document).ready( function(e) { $.ajaxSetup({cache:false}); setInterval(function() { ...

What is the best method for purging a previously stored variable from the cache when making an Ajax call and simultaneously passing a

I am encountering an issue with variable loading during the ajax call. Upon clicking, I pass a variable to the ajax call which then sends the value to a PHP script. The data obtained is from: rnc.csv DLRNC01 DLRNC02 DLRNC03 DLRNC04 DLRNC05 DLRNC06 DLR ...

Prevent the layout from shifting with CSS

I am faced with a challenge regarding a grid of images that are dynamically generated on the screen. The number of images in each row of the grid is dependent on the size of the page. While everything functions properly when the page is at a certain size, ...

When trying to use ngModel with Angular, an error occurs where the property 'selected' cannot be created on a string

I'm currently attempting to utilize [(ngModel)] in the following manner: <div class="items"> <tbody> <tr *ngFor="let info of this.information"> <td> <input type="checkbox" [(ngModel)]="this.info.n ...

Implementing uniform column width in a Material-UI Grid

Looking for a way to create a single column layout with items of equal width using the Material-UI Grid system? Check out this sample code: <Grid container align="center" direction="column"> <Grid item className={classes.item}> < ...

Steps to modify the CSS of a custom component in Angular 8

I have been attempting to override the css of a custom component selector, however, my attempts have been unsuccessful. I have tried using ":ng-deep" but it hasn't worked. How can I go about finding a solution for this issue? app.component.html: < ...

Display a div in JQuery along with all of its associated label elements

Here is my HTML code: <div id="summarySpan" style="padding-left: 20px" hidden> <label id="currentStatusSummary" style="padding-left: 20px" /> <br /> <label id="currentMonitoringSummary" style="padding-left: 20px" /> < ...

JavaScript code using the Jquery library to retrieve the following article from 'cached memory'

I am aware of the easier CSS options for my question, but I am determined to learn JS (Jquery), so please bear with me. My plan: Menu-items are connected to articles within my content division. Initially, only the first article (#intro) is displayed. All ...

"Identify the protocol name (string) based on a specific port number in TCP/UDP communication

Is there a built-in function in any web-oriented language to return protocol names based on port numbers? For example, if we have the following code: protocol = get_protocol_name(22) print protocol We would expect it to print out "ssh". A more detailed ...

Adjust the value of an option within a select input using URL parameters

With regards to this page: I am in the process of developing a script that can extract a parameter from the URL to dynamically modify the select option, thus changing which vehicle is showcased alongside the Honda on the chart. I experimented with the fo ...

Exploring the process of updating initialState within react-redux

I am currently using react-redux to retrieve data from a MongoDB database and integrate it into my React App. Below is the structure I am working with: const initialState = { Level: [{ wId: Math.random(), Level1: [ { id: Math.rando ...

What is the best way to display a loading image and temporarily disable a button for 3 seconds before initiating the process of sending post data from another page via

Is there a way to display a loading image and disable a button for 3 seconds before sending post data from another page using AJAX POST? Once the OK button is clicked, I would like the loading image to appear and the <input type="button" value="Check" ...

send a json response from my webpage

I have recently developed an HTML code to construct a user form where individuals can input information into various text fields. Additionally, I have included a button on the page that is meant to gather all the entered data and transform it into a json f ...

Error: Attempting to access the 'email' property of an undefined element during registration

I am facing an issue with my if statement. Below is the code snippet that I am currently working with: ` app.post('/register', redirectHome, async (req, res, next)=>{ try{ const email = req.body.email; let password = req.bo ...

Where to position a button in the middle of a div that varies in size

I'm currently working with this code snippet: <div class="outer"> <ul class="list"> <li class="inner"> <div class="line">information1</div> <div class="line">hyperlink1</div&g ...

The canvas loadFromJson function fails to implement the font-family property

I have implemented the following code to display Google font and update the canvas: /* on change of font, load the preview and update the canvas */ $('#font').on('change', function () { $('.font_preview').show ...

CSS problem: Chrome scrolling overflow glitch (ghost margin/padding)

Hey there, I've run into a bit of an issue with two divs containing tables - one acting as a header and the other as a scrollable content area. Everything is working perfectly except for this mysterious border/margin that keeps appearing in Chrome on ...

Place the text below the adaptable div

Could anyone offer guidance on how to properly align text underneath responsive images within divs? The issue I'm facing is that the divs adjust smoothly based on the viewport size, but the text below them doesn't stay centered as intended. Whi ...

Keep your eyes peeled for updates in jquery movements

Is there a way to detect changes in HTML content? I have a button that adds more HTML, but when I save the data using ajax, it doesn't capture the added HTML. Currently, when I click save, the new HTML is not recognized. $("#more_column").click(func ...