jquery toggleClass not retaining previous click event

I came across a show/hide function that seemed promising for my issue, which I found here (credit to the original author). Inspired by this, I created a demonstration on JSFiddle (https://jsfiddle.net/q7sfeju9/). However, when attempting to show rows, it does not work as intended.

In the JSFiddle demo, if I first hide 'Level 1.2', followed by 'Level 1.1' and then 'Level 1', it works fine. But upon clicking 'Level 1' once more, only 'Level 1.1' and 'Level 1.2' should be displayed, not all sub-levels. Unfortunately, all levels and sub-levels are being shown instead. If any sub-levels are hidden, they should remain hidden until specifically clicked.

If anyone has a solution or guidance on how to achieve this behavior, I would greatly appreciate it.

Thank you in advance.

Update:

Please refer to the code snippet below -

    $('tr').click(function(event) {
      event.stopPropagation();
      var currentLevel = parseInt($(this).attr('class')),
        state = $(this).hasClass('hiding'),
        nextEl = $(this).next(),
        nextLevel = parseInt(nextEl.attr('class'));
      while (currentLevel < nextLevel) {
        nextEl.toggle(state);
        nextEl = nextEl.next();
        nextLevel = parseInt(nextEl.attr('class'));
      }
      $(this).toggleClass('hiding');
    });
    tr[class^="2"] td {
      padding-left: 20px;
    }

    tr[class^="3"] td {
      padding-left: 40px;
    }

    tr[class^="4"] td {
      padding-left: 60px;
    }
    <table id="test">
      <tr class="1">
        <td>Level 1</td>
      </tr>
      <tr class="2">
        <td>Level 1.1</td>
      </tr>
      <tr class="3">
        <td>Level 1.1.1</td>
      </tr>
      <tr class="3">
        <td>Level 1.1.2</td>
      </tr>
      <tr class="2">
        <td>Level 1.2</td>
      </tr>
      <tr class="3">
        <td>Level 1.2.1</td>
      </tr>
      <tr class="3">
        <td>Level 1.2.2</td>
      </tr>
      <tr class="4">
        <td>Level 1.2.2.1</td>
      </tr>
      <tr class="4">
        <td>Level 1.2.2.1</td>
      </tr>
      <tr class="1">
        <td>Level 2</td>
      </tr>
      <tr class="2">
        <td>Level 2.1</td>
      </tr>
      <tr class="3">
        <td>Level 2.1.1</td>
      </tr>
      <tr class="3">
        <td>Level 2.1.2</td>
      </tr>
    </table>

Answer №1

Make sure to verify the state of the children and implement an if/else statement to toggle them when necessary.

Is the following achieving the desired outcome? From what I gather, only immediate sublevels should be displayed when a level is expanded.

CODE SNIPPET

    $('tr').click(function(event) {
  event.stopPropagation();
  var currentLevel = parseInt($(this).attr('class')),
    state = $(this).hasClass('hiding'),
    nextEl = $(this).next(),
    nextLevel = parseInt(nextEl.attr('class'));
  while (currentLevel < nextLevel ) {
    nextEl.toggle();
    nextEl = nextEl.next();
    nextLevel = parseInt(nextEl.attr('class'));
  }
  $(this).toggleClass('hiding');
  hideChildren()
});

// the below function ensures that the children of the previously clicked row remain hidden
function hideChildren() {
$(".hiding").each( function() {
var currentLevel = parseInt($(this).attr('class')),
nextEl = $(this).next(),
    nextLevel = parseInt(nextEl.attr('class'));
  while (currentLevel < nextLevel ) {
      nextEl.hide();
    nextEl = nextEl.next();
    nextLevel = parseInt(nextEl.attr('class'));
  }
})
}
tr[class^="2"] td {
  padding-left: 20px;
}
tr[class^="3"] td {
  padding-left: 40px;
}
tr[class^="4"] td {
  padding-left: 60px;
}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table id="test">
      <tr class="1">
        <td>Level 1</td>
      </tr>
      <tr class="2">
        <td>Level 1.1</td>
      </tr>
      <tr class="3">
        <td>Level 1.1.1</td>
      </tr>
      <tr class="3">
        <td>Level 1.1.2</td>
      </tr>
      <tr class="2">
        <td>Level 1.2</td>
      </tr>
      <tr class="3">
        <td>Level 1.2.1</td>
      </tr>
      <tr class="3">
        <td>Level 1.2.2</td>
      </tr>
      <tr class="4">
        <td>Level 1.2.2.1</td>
      </tr>
      <tr class="4">
        <td>Level 1.2.2.1</td>
      </tr>
      <tr class="1">
        <td>Level 2</td>
      </tr>
      <tr class="2">
        <td>Level 2.1</td>
      </tr>
      <tr class="3">
        <td>Level 2.1.1</td>
      </tr>
      <tr class="3">
        <td>Level 2.1.2</td>
      </tr>
    </table>

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 unsightly square surrounding my sprite in Three.js

I am attempting to create a beautiful "starry sky" effect using Three.js. However, I am encountering an issue where my transparent .png star sprites have a colored outline around them. Here is the sprite I am using: https://i.sstatic.net/2uylp.png This ...

Using inertia-links within the storybook framework

Hey there, just wanted to share my experience with storybook - I'm really enjoying it so far! Currently, I'm facing a challenge while implementing it in my Laravel app with Inertia. I'm trying to render a navigation link component that make ...

AngularJS - Always keep an eye on a group of items

Looking to create a custom watcher for a collection within my application, I initially believed that Angular would have all the necessary tools at my disposal. I had access to $watch, both shallow and deep, as well as $watchCollection. A $digest cycle was ...

Transfer text from one form to a text field on a different website

I've created a form that allows users to input numbers in a field and then directs the page to a specific URL. Here's the code snippet: <html> <head> <meta charset="utf-8"> <title>Tracking</title> </head& ...

What's the best way to create flying text effects - using CSS or JavaScript

Looking for a way to enhance the user experience of my shopping cart on Android and iPhone/iPod, I want to implement a feature similar to the iTunes Store where the price flies down to the total when a purchase is made. Since I use jQuery (not UI) on this ...

I do not prefer output as my optimal choice

My preference is to create drill down buttons rather than focusing on output. Currently, the output appears as: https://i.sstatic.net/8qs5F.png The content of index.html is as follows: <html>  <head> <script type="text/javascript" ...

Is it possible to turn a <span> element into a clickable hyperlink?

Can a span be turned into a clickable link? I have successfully made a span with only a background image (using the Gilder/Levin image replacement technique) into a clickable link. This seems to work well on my desktop in Chrome, Opera, and IE 11. Is thi ...

How can I launch five separate instances of Chrome on a Selenium grid, each with a different URL?

I have a list of URLs saved in a JSON file, structured like this: { "urls": [ "http://www.google.com/", "http://www.stackoverflow.com" ] } Currently, these URLs are being opened sequentially by the Selenium WebDriver JavaScript manager on a ...

Tips on utilizing media queries to optimize website layout for mobile devices

I'm currently working on a responsive website and utilizing media queries for that purpose. However, I've encountered an issue where the media queries don't seem to apply when the browser window is set to mobile view. Below is the snippet of ...

The individual HTML content does not appear in Fancybox; instead, it is displayed as part of a gallery

Facing an issue with a single HTML file not displaying in fancybox as expected. Instead of opening individually, it is appearing as part of a gallery with next and prev buttons. Is there a way to hide or disable these navigation buttons? ...

Resolving the issue of the 'Failed to load resource: net::ERR_FILE_NOT_FOUND' error

I'm encountering issues with loading my CSS in different browsers when using the "Copy Path" feature in VSCode. While everything displays correctly in preview mode within VS, none of the styles appear when pasting the path into Chrome or Edge. Below ...

I am currently working on a website that offers different themes, and I am attempting to update the iframe to reflect the selected theme on the site

I'm feeling lost on how to accomplish this task. Despite my efforts, I have been unable to find a solution so far. Perhaps utilizing javascript might be the key here, yet I am uncertain about integrating it into the existing script that I use for modi ...

Querying val results in an empty string being returned

In my application, I have the following HTML code snippet: <tr style="cursor:pointer;"> <td>100101</td> <td>Monkey</td> <td>Nuts<td> <td>Cow</td> <td>Soup</td> <t ...

Angular log out function to automatically close pop-up windows

Within my application, there is a page where users can open a popup window. When the user clicks on logout, it should close the popup window. To achieve this, I have used a static variable to store the popup window reference in the Global.ts class. public ...

Error occurred when trying to run 'npm run dev' on vite: Unable to access the file "node_modules/react/jsx-dev-runtime.js"

After successfully creating a Vite app, I encountered three errors when trying to run the app with npm run dev: [ERROR] Cannot read file "node_modules/react/jsx-dev-runtime.js": Access is denied. [ERROR] Cannot read file "node_modules/react/index.js": Acc ...

The addEventListener function seems to encounter issues in IE11

There is a javascript function below that uploads the selected file and updates the grid. It works perfectly in Firefox, but there seems to be an issue with IE11. The "ESignature/Registration" function within the addEventListener does not seem to execute ...

AJAX list refresh, fetch additional items and tally

Looking for a solution to update the values of listUsernames and numUsernames after adding an item? Check out this scenario: <ul id='usernameList'> <li class='username'>John</li> <li class='username&apo ...

What is the best way to assign a variable with the type (x:number)=>{y:number,z:number}?

I am trying to initialize a variable called foo, but my current code is not compiling successfully. let foo: (x: number) => {y:number,z: number} = (x) => {x+1, x+2}; This results in the following error: Left side of comma operator is unused and ha ...

navigation menu 'selective emphasis' feature

I have created a JQuery script that will highlight the 'About', 'My Projects', or 'Contact Me' text on the navigation bar when the corresponding section of the page is in view. To achieve this, I am using a scroll() event list ...

I am having trouble with getting the templateUrl to function properly

Recently diving into Angular, I am currently working with Angular-UI-Router in combination with ASP.NET MVC 4. app.config(['$urlRouterProvider', '$stateProvider', function ($urlRouterProvider, $stateProvider) { $urlRouterProvider.other ...