Simple Way to Modify Color of Active Page Link - HTML, CSS, and JavaScript

I found a helpful example on how to change link colors for the current page here.

Here is the script I added:

<script>

// current page highlight
    $(document).ready(function() {
    $("[href]").each(function() {
        if (this.href == window.location.href) {
            $(this).addClass("active");
            }
        });
    });

</script>

I inserted this script into the <head> section of these files: index.html (the home page), about.html, and store.html

For our website. Service links should not be highlighted, and Blog and My Account are currently inactive.

I then defined the corresponding style in my CSS:

.active {
color:#337ab7;
}

So when we're on the Home page (index.html), the Home link should display in color #337ab7, similarly for About and Store pages.

However, I am still not seeing any changes. Do I need to modify anything in the JavaScript, CSS, or HTML to make it work properly?

Below is the HTML code for the Navigation Menu in question:

UPDATE: Applied active class to the relevant links:

<nav class="navbar navbar-default">
<div class="container">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <div>
            <a class="navbar-brand" href="http://nowordpress.gatewaywebdesign.com/">
            <img src="assets/images/gatewaylogo.png">
            </a>
        </div>
    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav navbar-right">
            <li><a href="http://nowordpress.gatewaywebdesign.com/index.html" class="active">Home <span
                    class="sr-only">(current)</span></a></li>
            <li><a href="http://nowordpress.gatewaywebdesign.com/about.html" class="active">About</a></li>
            <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                   aria-expanded="false">
                    Services
                    <span class="caret"></span>
                </a>
                <ul class="dropdown-menu">
                    <li><a href="http://nowordpress.gatewaywebdesign.com/website-design.html">Website Design</a></li>
                    <li><a href="http://nowordpress.gatewaywebdesign.com/graphic-design.html">Graphic Design</a></li>
                    <li><a href="http://nowordpress.gatewaywebdesign.com/promotional-products.html">Promotional Products</a></li>
                    <li><a href="http://nowordpress.gatewaywebdesign.com/search-engine-marketing.html">Search Engine Marketing</a></li>
                    <li><a href="http://nowordpress.gatewaywebdesign.com/wordpress-conversion.html">WordPress Conversion</a></li>
                </ul>
            </li>
            <li><a href="/store.html" class="active">Store</a></li>
            <li><a href="#">Blog</a></li>
            <li><a href="#">My Account</a></li>
        </ul>

        </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
</nav> 

Once again, here is the live site. Appreciate your assistance.

Answer №1

SOLUTION

As an illustration, consider the store page:

HTML:

<li><a class="active" href="/store.html">Store</a></li>

CSS: (

.navbar-default .navbar-nav > li > a
was prioritizing the .active class, highlighting by doutriforce)

.navbar-default .navbar-nav > li > a.active {
color: #337ab7;
}

.navbar-button:hover, a.active {
color: #337ab7;
transition: ease-in-out 0.3s;
}

JavaScript:

// current page highlight

   // link color code initiates
    $(document).ready(function () {
        console.log("current page", window.location.href);
        $("[href]").each(function () {
            $('a[href]:not([href=#])').each(function () {

                if (window.location.href.indexOf($(this).attr('href')) > -1) {
                    console.log($(this).attr('href') +" is active ");
                    $(this).addClass('active');
                }
                else {
                    console.log($(this).attr('href') + "is not active ");
                }
            });
        });
    });
    // link color code completes

Ensure to modify which <a> link receives the active class based on the currently active page in your document - for instance, if you're modifying login.html, then your HTML should resemble this:

<li><a href="/store.html">Store</a></li>
<li><a href="/blog.php">Blog</a></li>
<li><a class="active" href="/login.html">Login</a></li>

If you're working on blog.php, then your HTML will appear like this:

<li><a href="/store.html">Store</a></li>
<li><a class="active" href="/blog.php">Blog</a></li>
<li><a href="/login.html">Login</a></li>

And so forth.

To wrap up, in index.html (the homepage), include a span with the class sr-only after the link text, as shown below:

<li><a href="http://nowordpress.gatewaywebdesign.com/index.html">
Home <span class="sr-only">(current)</span></a></li>

To conceal the (current) tag using Bootstrap.

Answer №2

The style of your .active class is currently being overridden by the class

.navbar-default .navbar-nav > li > a
.

To resolve this issue, you should adjust the CSS selector to be more specific by changing it from just .active to

.navbar-default .navbar-nav > li > a .active
.

If you only want to add the class active to the current accessed href, consider implementing the following code snippet:

$('ul.nav > li > a').each(function(){
   var url = window.location.href;
   var href = $(this).prop('href');

   if (url == href) {
     $(this).addClass('active');
   }
});

Alternatively, as suggested by @Mohamed-Yousef, you can simplify the process with:

$("a[href*='" + window.location.href + "']").addClass('active');

This method is particularly useful when comparing full URLs.

Answer №3

Avoid using the .each() method, you can simply utilize a selector instead

<script>
// highlighting the current page
    $(document).ready(function() {
       $("a[href*='"+ window.location.href +"']").addClass('active');
    });
</script>

If you want to understand how the

a[href*='"+ window.location.href +"']
selector functions, it essentially searches for an a tag with an href that contains window.location.href. If you alter your href attribute to something like
<a href="/website-design.html">
, this selector will no longer be operative. In such cases, you would need to use .each() in combination with .indexOf()

<script>
// highlighting the current page
    $(document).ready(function() {
       $('a[href]:not([href=#])').each(function(){
            if(window.location.href.indexOf($(this).attr('href')) > -1){
               $(this).addClass('active');
            }
       });
    });
</script>

Answer №4

Error on line 19 of about.html: Uncaught SyntaxError due to an invalid or unexpected token.

A strange unicode character in line 19 is causing a parsing error, which can be observed in Chrome's inspector within the "foreach" section.

Removing that unicode character may resolve the issue.

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 minified version of Bootstrap's CSS will only be loaded when I explicitly import it in my index

I used to rely on BootstrapCDN for my styles, but now I want to download the files and use them locally. However, when I try to load the styles without an internet connection, they don't seem to work properly, especially the grid layout. My current s ...

Create a Bootstrap grid that perfectly fits the viewport without any overflowing content

I'm currently utilizing Bootstrap 5 in an attempt to design a simplistic layout consisting of an MxN grid of cells, each of equal size. My goal is to have this grid fill the entire viewport without any scrollbars appearing in either direction. However ...

Looping through arrays within objects using NgFor in Angular 2/JavaScript

I have a custom object with data that I am iterating through using ngFor. Within this object, there is an array component that I also want to iterate through in a <li></li>. Currently, the output appears as one complete string within each < ...

Deciding on excluding empty key:value pairs from an object for various filtering needs

One of the features in my app allows users to filter results by "blood group" and "city", along with other areas. The information is retrieved from a database using Axios for Vuejs, incorporating query strings within the URL. For example: http://example.co ...

What is the reason why calling setState does not update the local state?

Hello everyone, I came across an intriguing React task and I'm struggling a bit with finding the solution. Task: Can you figure out why this code isn't working and fix it? Code: class BugFixer extends React.Component { constructor(props) { ...

The onRendered function fails to load all data in the template

I'm dealing with a frustrating bug that I just can't seem to fix. I've been attempting to load all users using Users.find() into one of my layout sub-templates, but for some reason, it's not working as expected. Instead of loading all u ...

Ensure that dynamically generated fields are verified whenever one of them is modified

I am working on a program that generates text boxes and drop down lists dynamically. I need to find a way to validate these fields only when one of them is changed. The validation should occur if a date is entered in the text box, it should then check if t ...

What is the way to execute a function *once* all my ajax call functions have finished?

I am utilizing jQuery to execute some ajax requests: var information = {}; function process_information(item){ information[item.id] = item; } function perform(){ var calls = []; for(var i = 0; i < 10; i++){ var call = $.get(URL, ...

Difficulty encountered while implementing Ajax POST in CodeIgniter

I've been working on a project similar to a ticket system that occasionally requires lengthy answers. When using CKEDITOR in the answer area, the agent's changes are automatically saved to the database using Json GET. However, I encountered an er ...

AngularJS scope watch isn't firing as expected

In the scope, I store a filtering string for dates. $scope.myModel = {date:""}; Utilizing a jQuery datepicker, <input date-value="myModel.date" date-picker /> This directive updates the string through AngularJS - Attribute directive input value c ...

Disappearance of jQuery Ui Spinner on Woocommerce cart page occurs after cart update

I've encountered a problem and am struggling to find a solution. Currently, I am utilizing the jquery ui spinner in the product quantity section to set minimum and maximum quantities for each product. This allows users to increase the quantity by the ...

Left-hand navigation panel that complements entire screen

Web Design .sidenav { height: 100%; position: relative; overflow-y: scroll; background: #000000; width: 15%; } Ensuring the menu covers the full screen correctly by setting its height to 100% is effective, but it may appear awkward wh ...

Exploring the Structure of Trees using JavaScript

Here are my terms: var terms = [ { id: 1, name: "Name 1", parent: null }, { id: 2, name: "Name 2", parent: 6 }, { id: 3, name: "Name 3", parent: null }, { id: 4, name: "Name 4", parent: 2}, { id: 5, name: "Name 5", ...

Subtracting 25% from the width of the web browser

After spending some time trying to solve this issue by myself, I've decided to reach out for help here where I know I can get some great responses. I am looking to determine the dimensions of the browser window minus 25%. Specifically, I have a two-c ...

The HTML link is not directly attached to the text, specifically in Internet Explorer

When viewing my website in Chrome, the menu links in the Header function correctly. However, in Internet Explorer (specifically version 11), hovering over 'HOME,' 'LISTINGS,' or 'AGENTS' reveals that the displayed URL is incor ...

Having trouble with hover effects not working on links due to the container? Here's a solution for you

I would like to create a layout with 3 columns for menu, story, and description. Each story should have its own unique description. Everything was working fine until I added a div to the middle column. The same issue arose with the right column but I manag ...

The delete_node() function in jstree does not seem to be removing nodes

In my attempt to create a custom context menu for different nodes, I've managed to display different labels for clicks on folders or files. However, I am facing some challenges when trying to delete them. Take a look at my code snippet. Due to diffic ...

How can I adjust the size of posts on the Tumblr Official Theme?

The size of posts on the Tumblr Official Theme caught my attention recently. It seems they are set at 500px, causing photos posted on the blog at the original dash post size of 540px to be compressed. I've examined the coding for the theme but can&apo ...

Jquery's Ajax Promise fails to execute

I'm developing an app and encountering difficulties with firing a promise. I simplified the code to a basic example that is still not functioning, utilizing EasyPHP... ajaxDialog = function( target ) { // Promise to indicate completion return ...

Tips for resolving the issue of loading not appearing on screen in Angular

How can I resolve the problem of the loading animation not appearing? Below is the code snippet: HTML <div *ngIf="tempThermometer | async as temp; else loading"> <ng-container *ngIf="temp.length !== 0; else noItems"> &l ...