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

Comparing Data Manipulation Techniques: Server Side vs Client Side Approaches in Reddit API Integration

As I delve into creating a simple Node/Express web application that fetches data from the Reddit API, performs some alterations on it, and intends to present this information using Charts.js on the client side, I find myself facing a dilemma due to my limi ...

Saving users' dark mode preference on my website

I recently implemented a dark mode feature on my website. However, I noticed that when I enable dark mode and then refresh the page or navigate away, the preference resets. To address this issue, I am looking to store the user's preference as a cookie ...

Pass the $scope object from a controller to a modal controller

I am facing an issue with transferring the $scope variable from ctrlone to ctrltwo, which is a modal window on my page. When I open the modal in ctrlone, my code looks like this: var modalInstance = $modal.open({ templateUrl: 'Modal.html&ap ...

Tips for incorporating properties from JSON-retrieved objects into a template

I'd like to extract and display only the state_name value from the HTML template. Is there a way to achieve this using jQuery in the template? $.ajax({ type: 'GET', url: "http://localhost:8000/country_state/", data: { "country": s ...

Create a modal using the base of a[href^=“#id”]

What is the best way to minimize a call modal window? $('#button-1').on('click', function() { $('#modal-1').addClass('j-modal--open'); }); $('#button-2').on('click', function() { $(' ...

Struggling with passing parameters through a route and displaying them in the Reddit app using React?

I'm currently working on a project that involves displaying threads from various subreddits when a user clicks on a list item using routes and react. However, I've encountered some issues with getting the information to display correctly. Below i ...

Is there a way to obtain cookies on a Server-side component in the latest version of Next.js?

import axios from "axios"; const Api = axios.create({ baseURL: "http://127.0.0.1:5000", }); axios.defaults.headers.common["Authorization"] = cookie; In server-side environment, document.cookie is not accessible. Alternat ...

"Real-time image upload progress bar feature using JavaScript, eliminating the need for

I have successfully implemented a JavaScript function that displays picture previews and uploads them automatically on the onchange event. Now, I am looking to add a progress bar to show the upload status. However, all the solutions I found online are rel ...

Handling the width and borders of CSS cells that are positioned outside of a table

Welcome! I recently created a simple gantt organizer as part of a demo. My goal was to make the main table scrollable while keeping certain columns "frozen" for easy visibility when navigating through the data. To achieve this, I followed some advice found ...

Comparing form submission with a button click to pass data using Ajax - success in one method but failure in the other

I am facing an issue with two pieces of jquery code in my Flask application. While one works perfectly, the other is not functioning as expected. Both the form and a button trigger the same function through ajax calls. Currently, for troubleshooting purpos ...

Guide on converting AS3 to HTML5 while incorporating external AS filesAlternatively: Steps for transforming AS

I've been given the challenging task of transforming a large and complex Flash project into html5 and javaScript. The main stumbling block I'm facing is its heavy reliance on external .as files, leaving me uncertain about the best approach. Most ...

Change the class of <body> when the button is clicked

One of my tasks involves adding a button that, when clicked, should give the body the class "open-menu". Implementing this using jQuery was quite straightforward - I just needed to add the following line of code: $('.burger').click(function() ...

Transfer data accurately from main window to fancybox iframe

Seeking assistance with a Wordpress plugin I've created using PHP. It's a gallery plugin that allows users to add captions and custom fields for images. The forms are displayed in a Fancybox modal, triggered by clicking input buttons. Here is an ...

Dynamic font size that adjusts as you change the window dimensions

Is there a way to adjust the font size in HTML so that when I resize the window, the text size adjusts accordingly? It's like setting a percentage for the text based on the size of the container it is in. Let me provide an example of what I have in m ...

Guide to accessing HTML elements and saving them in a JSON formatted text using JavaScript

If you have an html form with labels, select boxes, and radio buttons, you can use javascript to store the child elements of that form in a json string format. Here is an example: { "label": { "content": "This is a label" }, "textbox" ...

Removing the border from a button in CSS and HTML

Looking to build a sleek and stunning website, but struggling with removing button borders. Any help would be greatly appreciated! If you'd like to check out the issue, visit this link: . I'm aiming for no button or image borders. To review my ...

When the settings are saved in PHP and AJAX, the password fields are automatically cleared

On my settings page, users can update their information. All fields are working correctly except for the password field. Currently, when a user clicks submit, it updates the password to nothing in the MySQL database. What I want is for nothing to happen in ...

Updating style of element in EJS following POST request in Node.js using Express

I am working on a form page that is supposed to display a Success Alert (Boostrap) once the user fills out the form and clicks the Submit button. <form class="well form-horizontal" action="/contact" method="post" id="contact_form"> ... (input fiel ...

Tips on updating CSS styles for navigation bar links in real time

Currently, my homepage displays a CSS content hover effect when the user interacts with the icons. However, I am facing an issue where all icons show the same text "home" on hover. How can I customize the text output for each individual icon/link? Your hel ...

How can I determine if a URL in react js includes a specific string?

I am working on a project where I need to check if a given URL contains the string youtube using react hooks in React JS. This is what my current code looks like: useEffect(() => { let srcLink = "www.google.com/https://img.youtube.com/vi/h9-qcy3HQn ...