Unable to assign a class to the menu option

I'm encountering an issue with the following code:

JavaScript

$(document).ready(function() {
  var url = window.location;
  var element = $('#nav1 li a').filter(function() {
    return this.href == url || url.href.indexOf(this.href) == 0;
  }).parent().addClass('navigation__active');
  if (element.is('li')) {
    element.addClass('navigation__active').parent().parent('li').addClass('navigation__active')
  }
});

HTML

<ul id="nav1" class="navigation">
<li class="navigation__active"><a href="#"><i class="zmdi zmdi-home"></i> 
   Home</a></li>

 <li class="navigation__sub">
    <a href="#"><i class="zmdi zmdi-view-week"></i> About</a>
    <ul>
        <li><a href="#">History</a></li>
        <li><a href="#">Team</a></li>
        <li><a href="#">Projects</a></li>
    </ul>
</li>
  <li class="navigation__active"><a href="#"><i class="zmdi zmdi-home"></i> 
    Contact</a></li>
 <ul>

I have successfully implemented the functionality to select items under About like History, Team, Projects. However, I am facing a problem where the navigation__active class is not being applied when clicking on Home or Contact. Is there a solution for this?

Answer №1

If you're aiming to add a class to the currently selected menu item based on the URL in the address bar, my suggestion would be to develop it as a single-page application. This way, you can monitor the menu state and dynamically update the page content according to the chosen menu item.

However, if you prefer to proceed with the current approach, the provided code seems to align more closely with what you are trying to achieve compared to your initial attempt. Although there are some hardcoded elements, they serve as a reference point for identifying where mistakes may have occurred in the JavaScript section.

$(document).ready(function() {
  var url = {href: "https://stacksnippets.net/test"};
  var element = $('#nav1  li a').filter(function(index, el) {
    return url.href === el.href;
  });
  
  var selectedElem = $(element[0]);
  
  if (selectedElem.parent().is('li')) {
    selectedElem.parent('li').addClass('navigation__active')
    var parentMenuItem = selectedElem.parent('li').parent('ul').parent('li');
    parentMenuItem.children('a').addClass('navigation__active')
  }
});
.navigation__active {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul id="nav1" class="navigation">
  <li>
    <a href="#"><i class="zmdi zmdi-home"></i> Home</a>
  </li>

  <li class="navigation__sub">
    <a href="#"><i class="zmdi zmdi-view-week"></i> About</a>
    <ul>
      <li><a href="#">History</a></li>
      <li><a href="test">Team</a></li>
      <li><a href="#">Projects</a></li>
    </ul>
  </li>
  <li>
    <a href="#"><i class="zmdi zmdi-home"></i> Contact</a>
  </li>
 <ul>

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

A guide on extracting data from a mongoose model and assigning it to a variable in a manner similar to the MVC design pattern

Below is an example of MVC framework code in PHP. I'm seeking advice on how to implement a similar process in Node.js using Mongoose. I am working with Node.js, MongoDB, and REST API development. Controller file: <?php class Myclass { public fu ...

Could this truly be jQuery in action?

Once more, here is some code snippet: audioElement.addEventListener('ended', function() { $('span#pause').fadeOut('slow'); $('span#play').delay(1500).fadeIn('slow'); }); I believe that "addEventLi ...

Total Output Calculation

In my latest coding project, I have crafted a unique algorithm to calculate exam scores with the inclusion of interactive buttons! function incorrectResponse() { var calc = 0; var calc2 = 1; var divElement = document.createElement("div"); divEle ...

Steps for retrieving the currently selected text inside a scrolled DIV

An imperfect DIV with text that requires a scroll bar For example: <div id="text" style='overflow:scroll;width:200px;height:200px'> <div style='font-size:64px;'>BIG TEXT</div> Lorem Ipsum is simply dummy text of th ...

An issue with Ajax's syntax

Help needed with my ajax code. I'm encountering an error while trying to send data in Ajax - specifically with the data syntax. Despite several attempts, I have not been able to successfully resolve this issue. Here is the portion of code causing tro ...

Encountering an error while setting up the object spread operator Babel plugin for ES201

Exploring the possibilities of the new ES2018 spread operator for objects led me to discovering a promising NPM package: babel-plugin-transform-object-rest-spread Here's a glimpse of my package.json: // Scripts section "scripts": { "dev": " ...

Tips for adding new elements to an array within an object

Here is a snippet of my current JSON data: { "_id" : 393, "item" : 34, "comments" : [ { "name" : "kevin", "messages" : [ "item", "item" ] }, { ...

Is it possible to create a system in NextJS that utilizes either the path or the query parameter?

Due to historical reasons, there is a need to maintain a blog link structure that resembles /blog?article=id-of-article. However, the goal is to implement pre-rendering with NextJS and have the blog URL appear as /blog/id-of-article. What is the most effe ...

Strategies for resolving duplicate jQuery code in my project

Trying to simplify my jQuery code that handles video selection and playback functionality. Users can click on a thumbnail or button to play a specific video, with the title of the video changing accordingly. Despite achieving the desired outcome, the cur ...

Create a sinusoidal wave and stream it through the web browser

I'm looking for a code snippet that can: create a sine wave (an array of samples) play the wave This should all be accomplished in a web browser using an HTML5 API in JavaScript. (I've tagged this with web-audio, but I'm not entirely ...

In a multi-user environment, querying FaunaDB may not always retrieve the most up-to-date results

Background I've been delving into FaunaDB alongside React and managed to create some code with inspiration from this article. The project I'm working on involves a coffee poll/counter app - users are presented with various types of coffee and ca ...

Using AngularJS to display a targeted row in a table

I am currently working with a basic table and using ng-repeat to display rows in the table. I have a specific requirement where I want to show an additional row when a regular row is clicked. This additional row should contain custom markup in just one co ...

A guide on unpacking errors returned from a backend and sent out as an Error object in JavaScript

After investigating, it turns out that the issue lies with how the Error object constructor handles the response object passed to it in the catch error handler. The SDK I am using contains a method which can be found at this link to sdk code /** ...

Transforming an image object into a File object using Javascript

My goal is to utilize HTML5 on the client side in order to convert an "image object" into a "File object" for uploading to azure blob storage. I am working with AngularJs and my approach involves: Converting the image to a file Uploading the file to blob ...

In ES6, instantiate a fresh new instance of this

Can a new instance of self/this be generated using ES6 inside a static method? For instance; class myClass { static model() { return new this; } } Is there a standard approach for this situation? Thank you very much. ...

What is the best way to handle sequential $http calls in AngularJS? Specifically, I want to make the second $http call dependent on the response of the first

When making two $http calls, the second call should only be executed based on the response from the first call if there is an error present. ...

Having trouble obtaining search parameters in page.tsx with Next.js 13

Currently, I am in the process of developing a Next.js project with the Next 13 page router. I am facing an issue where I need to access the search parameters from the server component. export default async function Home({ params, searchParams, }: { ...

Using PHP to query the database and render text and links in the menu

On my website, users currently choose an "event" from a dropdown menu that is populated from a database (Check out the code below). Once a user selects an event from the menu, I want to display text links or a second dropdown menu with the "locations" ass ...

What is the best method to transfer text entered in one textarea to the output of another?

I recently picked up JavaScript again and encountered an issue while developing an app. I am struggling to pass input from one textarea to another, where the text should be converted to uppercase. I attempted to tweak code from w3, but I prefer to achieve ...

Using multiple instances of the Summernote Wysiwyg editor on a single page with identical placeholders

I have been using summernote successfully in my application, but I have encountered a minor issue where I have 2 editors on one page. The placeholder in the second editor seems to be inheriting the placeholder of the first editor. Is there a simple solut ...