Track and maintain the active status of the clicked article using jQuery

I'm encountering an issue with jQuery where the parent ul li does not open as expected. Below is the structure of my HTML:

<div>
  <ul>
     <li class="has-sub">
        <a href="#">1</a>
        <ul>
           <li><a href="#">1.1</a></li>
           <li><a href="#">1.2</a></li>
           <li class="has-sub">
             <a href="#">2</a>
             <ul>
                <li><a href="#">2.1</a></li>
                <li><a href="#">2.2</a></li>
                <li class="has-sub">
                  <a href="#">3</a>
                  <ul>
                      <li><a href="#">3.1</a></li>
                      <li><a href="#">3.2</a></li>
                      More...
                  </ul>
                </li>
             </ul>
           </li>
        </ul>
     </li>
  </ul>
</div>

jQuery:

$(function () {
  $('a').each(function () {
    if ($(this).prop('href') == window.location.href) {
        $(this).addClass('activation');
    }
  });
});

css:

.open > a:after,
.open > a:before {
 -webkit-transform: rotate(45deg);
 -moz-transform: rotate(45deg);
 -ms-transform: rotate(45deg);
 -o-transform: rotate(45deg);
 transform: rotate(89deg);}

activation class is added, but it does not open the parent ul li. I want the parent ul li to open when the class is activated.

How can I achieve this desired solution?

Answer №1

Here is a snippet that may help with your issue:

$(document).ready(function() {
  $('a').click(function() {
    if ($(this).attr('href') === window.location.href) {
      $('li').removeClass('open');
      $('a').removeClass('active');
      $(this).addClass('active').closest("li").addClass("open");
    }
  });
});

You can view the demo on JSFiddle

Feel free to inspect the structure using the browser's Inspect Element feature.

Answer №2

To implement the required functionality, you will need to incorporate the following JavaScript code:

$(function() {
  $('a').removeClass('activation');
  $('ul').removeClass('open');
  $('a').each(function() {
    if ($(this).attr('href') == '#') { //replace with your desired URL
      $(this).addClass('activation');
      $(this).parent().parent().addClass('open');
    }
  });
});

For a demonstration of this code in action, you can view a working DEMO

Answer №3

Here is my updated jQuery script:

$(document).ready(function () {
  $('a').each(function () {
    if ($(this).attr('href') == window.location.href) {
        $(this).addClass('active');
        $(this).parent().closest('.has-sub').addClass('open activate');
    }
  });
});

Currently, only the second position is functioning correctly while the third and fourth positions are not working.

Here is the corresponding CSS:

.active {
  visibility: hidden;
}

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

Exploring nested maps in JavaScript

I attempted to nest a map within another map and encountered an issue where the innermost map is being executed multiple times due to the outer map. The goal is to link each description to a corresponding URL (using # as placeholders for some links). Here ...

Directive's ng-click function fails to execute

This directive contains a function that should be executed when clicked. ebApp.directive('monthDir', function () { return { restrict: 'E', templateUrl: 'htmlFiles/monthDirective.html', transclu ...

When clicked, the menu disappears successfully with the "show" functionality, but unfortunately, the "hide" feature is not working as intended

Within my menu, I have a section for portfolios that transforms into a dropdown on desktop hover and mobile click. The issue arises on mobile devices where the first click displays the menu correctly, but subsequent clicks do not trigger any change. I att ...

What is causing the issue with transmitting the server datetime to my local jQuery script?

I am facing an issue with my timeoftheserver.php page setup. The PHP code is quite simple: <?php echo date('D, d M y H:i:s'); ?> Similarly, the script on my local machine is also straightforward: var today; try { today = new Date($. ...

execute the middleware function within the router

I've integrated sessions in my express.js application using Mozilla's client-sessions and I'm encountering an issue. My post and get requests are in router.js, while the middleware is in app.js. When I try to run it, I receive the following ...

Issue with flex item not expanding to fill entire height within flex container

My markup contains the following code: .container { display: flex; width: 500px; } .col1 { background: red; height: 100%; width: 50px; } .col2 { background: blue; flex: 1; height: 200px; } <div class="container"> <div class= ...

Exploring and deciphering the intricacies of the underlying technology

Apologies if this question seems misplaced, but as a complete beginner, I'm a bit lost. Let's consider this website as an example: I'm trying to uncover the libraries and technologies employed in the background to learn more and replicate ...

Can JavaScript be used to create a CSRF token and PHP to check its validity?

For my PHP projects, I have implemented a CSRF token generation system where the token is stored in the session and then compared with the $_POST['token'] request. Now, I need to replicate this functionality for GitHub Pages. While I have found a ...

Tips for identifying the most effective element locator in the DOM with Playwright

Currently, I am in the process of incorporating Playwright tests for a website that supports multiple locales. The majority of the page content is dynamically generated from CMS content (Contentful). I am hesitant about using hardcoded text locators like ...

Flatbuffers does not exist in this context

Currently, I am working on a nodeJs application that involves the use of Google Flat Buffer. After installing flatc on my MacBook Pro, I compiled the schema below: namespace MyAlcoholist; table Drink { drink_type_name: string; drink_company_name: stri ...

Retrieve Extra Information as You Scroll Down a Webpage with jQuery's Ajax Functionality in ASP.NET

I recently attempted to implement the feature mentioned in the title into my project and decided to test it out to see how it functions. However, during testing, I encountered a client-side script error displaying the message Undefined when I reached the b ...

Can a condition be incorporated in a gulpfile to execute a task depending on the size of a file?

Currently, I am utilizing gulp for image compression. However, my requirement is to only compress images exceeding 200kb in size. Can JavaScript be used to loop through a directory and selectively run the minification process on files larger than 200kb? ...

Issue encountered when employing the spread operator on objects containing optional properties

To transform initial data into functional data, each with its own type, I need to address the optional names in the initial data. When converting to working data, I assign a default value of '__unknown__' for empty names. Check out this code sni ...

Adjust the size of the text within the div element as needed

Here is my code on jsFiddle where I am dynamically changing the text font to fit in the div. Everything is working perfectly fine. Currently, the text is within a span element, but I would like to remove the span and have the same functionality. However, w ...

What is the best way to evaluate the rows of two specific elements?

My validation process involves comparing individual rows in the clientDocument with the corresponding rows in the serverDocument, instead of comparing the entire documents at once. Currently, I am using the following code snippet for comparison: JSON.stri ...

Is it possible to decrease the size of a div by scrolling both vertically and horizontally?

Can a div's height and width both be reduced at the same time while scrolling down a page? Let's say that as the user scrolls, the size of the div changes from 400px by 400px to 200px by 200px, all while remaining centered on the page. I've ...

Creating a dynamic linear gradient background color using Angular 2 binding

Using static values works perfectly <div style="background: linear-gradient(to right, #0000FF 0%, #0000FF 50%, #FFA500 50%, #FFA500 100%);"></div> in my TypeScript file. this.blueColor = '#0000FF'; this.orangColor = '#FFA500&a ...

Angular 17 | Angular Material 17.3.1: Problem encountered with Angular Material form field focus and blur event handling

I attempted to apply (blur) and (focus) effects to my mat-form-field input field, but it seems like they are not working properly on my system. Here is a code snippet that resembles what I am using: html file <form class="example-form"> ...

The class name remains unchanged despite the change in value

I am currently working on a webpage that features two interactive tabs. The goal is to have one tab highlighted as "active" while the other remains inactive when clicked, and then switch roles when the other tab is selected. Below is the code snippet I ha ...

Transitioning backgrounds in a slideshow

I am attempting to create a unique slideshow effect for my page background by changing the image URL at specific intervals with a smooth fade in and fade out transition. However, I am faced with the challenge of figuring out the best way to achieve this. ...