If the URL matches the href of a link, include a class

I want to create a jQuery script within WordPress that will assign the "active" class to the sidebar element matching the URL of the corresponding link in the navbar.

(function ($) {
    var url = window.location.href;
    $('.navbar-nav li').each(function ($) {
        if ($('.navbar-nav li a').attr('href') == url) {
            $('.navbar-nav li').addClass('active');
        }
    });
    console.log(url);
})(jQuery);
.active {
background-color: black;}
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>


<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-white">
    <div class="collapse navbar-collapse" id="navbarTogglerDemo01">
      <ul class="nav navbar-nav">
        <li class="nav-item menu_accueil only-mobile">
            <a class="nav-link" href="<?php echo get_site_url() ?>/">
                Accueil
            </a>
        </li>
        <li class="nav-item menu_marque">
          <a class="nav-link" href="<?php echo get_site_url() ?>/la-marque-honey">
            La marque 
          </a>
        </li>
        <li class="nav-item menu_formule">
          <a class="nav-link" href="<?php echo get_site_url().'/la-formule-honey' ?>">
            La formule 
          </a>
        </li>
        <li class="nav-item menu_bebe">
          <a class="nav-link" href="<?php echo get_site_url() ?>/conseil">
            Le monde de bébé
          </a>
        </li>
      </ul>

    </div>
  </nav>

An error is displayed ( $ is not a function ), even though there is another part of the code on the site that works correctly using the same selectors.

What could be causing this issue? Thank you

Answer №1

An error message is displayed indicating that $ is not recognized as a function.

The reason for this error is that you were redefining the variable $ inside the each loop, which was causing the issue:

 $('.navbar-nav li').each(function ($) {
 // Do not redefine $ like this -------------------^

There were multiple issues in your code, but the main problem was that you were using selectors to target elements across the entire page instead of focusing on elements within each iteration of the each loop.

$(function() {

  var url = window.location.href;
  $('.navbar-nav li').each(function() {
    if ($('a',this).attr('href') == url) {
      $(this).addClass('active');
    }
  });
  console.log(url);


});
.active {
  background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />


<nav class="navbar fixed-top ">
  <div class="" id="navbarTogglerDemo01">
    <ul class="nav navbar-nav">
      <li class="nav-item menu_accueil only-mobile">
        <a class="nav-link" href="xxx">
                Home
            </a>
      </li>
      <li class="nav-item menu_marque">
        <a class="nav-link" href="xxx">
            The brand 
          </a>
      </li>
      <li class="nav-item menu_formule">
        <a class="nav-link" href="https://stacksnippets.net/js">
            The formula 
          </a>
      </li>
      <li class="nav-item menu_bebe">
        <a class="nav-link" href="xxx">
            Baby's world
          </a>
      </li>
    </ul>

  </div>
</nav>

Answer №2

Ensure that your jquery script is loaded before calling your function. To achieve this, place the jquery script tag before the script tag containing your code.

Upon fixing your initial mistake, the current setup will apply .active to each li element that is a descendant of .navbar-nav.

$('.navbar-nav li').each(function ($) {//Is $ in the function parameters needed?
    if ($('.navbar-nav li a').attr('href') == url) {
        $('.navbar-nav li').addClass('active');//Incorrect line
    }
});

Consider utilizing the this keyword in your code. You can try something like:

$('.navbar-nav li').each(function () {
    let anchor = $(this).children('a');
    if ($(anchor).attr('href') == url) {
        $(this).addClass('active');
    }
});

Answer №3

Give this a shot:

jQuery( document ).ready(function() {
    var currentUrl = window.location.href;
    $('.navbar-nav li').each(function () {
        if ($(this).find('a').attr('href') === currentUrl) {
            $(this).addClass('active');
        }
    });
    console.log(currentUrl);
});

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

Updating View in Angular 2 ngClass Issue

I'm encountering some challenges with updating my view using ngClass despite the back end updating correctly. Below is my controller: @Component({ selector: 'show-hide-table', template: ' <table> <thead> ...

Sort the observable data by a value returned from an API request

I am completely new to using RxJS and any assistance offered would be greatly appreciated! Within my component's HTML template, I am looking to create a radio button list. The values for this list are fetched from an observable using the async pipe. ...

"Encountering a problem with Javascript/jssh in Firefox version 4.0 beta

After creating jssh for Firefox 4.0b1 and converting it into an xpi file, I installed it on my browser. However, when trying to run a Javascript code that scans <td> tags in the onclick or onfocus events for a specific phrase, I encountered an NS_E ...

How to extract text from an HTML element using Selenium

In the following HTML snippet, I need to extract the text of elements 1 and 2 individually. <div class="sc-492bf320-0 sc-7d450bff-9 crIwBV juiSXn"> <div data-change-key="homeScore.display" class="sc-18688171-0 sc-7d450bf ...

Endless loop issue encountered while attempting to refresh token with Axios interceptors

I have a Vue.js single-page application. My objective is to refresh the token automatically via axios interceptors if it has expired. Before sending a request to the API, I need to check the expiration time of the token. If it has expired, I should refresh ...

recursive algorithm utilizing an array as an argument

Currently, I am in the process of developing a function that extracts chest exercises from an array titled "chest". This particular function is required to randomly select multiple exercises, achieved by utilizing a random pointer. In order to avoid selec ...

Creating an Image Slideshow on Your Website

I'm looking to create an image slideshow on my website that functions similarly to the one found at . However, I want the images to occupy the entire screen rather than having smaller images like the reference site. Can anyone offer guidance on how t ...

The dropdown list event does not seem to be triggering when JavaScript is implemented

Having trouble triggering a dropdownlist event. The dropdown in question: asp:dropdownlist id="ddlhello" Runat="server" AutoPostBack="True" onchange="javascript:return ChangeHeader();" An associated selectedindex change event has been added in the code ...

Fetching and displaying data from an array of objects in a table view using Swift

I am currently working on an app where I need to retrieve data from an API that I built using NODE.js, MongoDB, Express.js. My goal is to pull an array of objects from the API and create a table view based on these objects. Each cell in the table view cor ...

Is it effective to cancel a $timeout within the 'then' function?

I find myself doing this quite frequently, but I'm unsure if it's actually effective. How can I verify that it's working as intended? And if it's not, what is a more reliable way to cancel a timeout after it has finished? var delay = $ ...

Error: Module not found - The package path "." is not exported from the specified package. As a result, Firebase will not update in your Next.js

I have been developing a Next.js application that retrieves data from a Firebase collection. During the process of connecting to the Firebase database, I have come across the following error: Failed to compile. Module not found This error seems to be ori ...

Having trouble setting up a bootstrap Carousel. It's giving me some issues

I'm encountering an issue with my project where the carousel is not transitioning between images as expected. Here's a snippet of the code causing trouble: <!DOCTYPE HTML> <html lang="en"> <head> <meta ...

What is the best way to create a button with this functionality?

In the form that I have created, it is opened in a bootstrap modal style. This form contains a button that, when clicked, triggers an alert box to appear. The code snippet used for this functionality is as follows: echo "<script>"; echo "alert(&apos ...

Tips for comparing an array against a string and increasing a variable based on the outcome

I am currently working on a Javascript code snippet that aims to find specific strings in an array. var test = ['hello', 'my', 'name']; for (var i = 0; i < data.length; i++) { if (test === "name") { //In the ...

Mastering the fundamentals of integrating/augmenting a fresh template in Umbraco

Let me be completely honest. Umbraco is unlike any other CMS I have worked with before. I am currently struggling to grasp the proper method of creating a Template and integrating it into Umbraco. How exactly can I add a template? I am making changes to t ...

The process of enriching an ASP.NET hyperlink by making it both bold and under

I'm currently working on a webpage in asp.net. I have two hyperlinks and I want to make them active by applying a style sheet that makes them bolder and underlined, but for some reason it's not working. Here is the HTML: <li style="margin-le ...

What is the best way to display single data instance from API using Angular?

My API data is structured in a way that includes various questions and their corresponding options. I am looking to display one question and its alternatives at a time, with the ability to move to the next question upon clicking a "Next" button. Since the ...

What steps should I take to resolve the issue of 'this.reduce() not being a function'?

Here is my code : app.get("/", (req, res) => { const reducer = (acc, guildCount) => acc + guildCount; const results = client.shard.fetchClientValues('guilds.cache.size'); console.log(results) let guildCount ...

Utilize Javascript to reconfigure the JSON structure

Hey there, in my code I retrieve a JSON blob that has the following structure: [ { "ts": 1431736740, "aggs": { "DNS": { "min": 20, "max": 21, }, "SEND": { ...

Issue with dynamically adjusting flex box width using JavaScript

Currently, I am developing a user interface that heavily relies on flexbox. The layout consists of a content area and a sidebar that can be toggled by adding or removing a specific class. Whenever the sidebar is toggled, the content area needs to be manua ...