jQuery sliding toggle effect combining multiple div sets

I have two columns, A & B. Some items in A open multiple items in B. A will toggle its corresponding B Items - BUT clicking on an A that includes an already opened B starts to mess up the toggle.

I want each item in A to open its respective items in B and if one or more of those items are already open then don't close them. Clicking on A again should close its corresponding items in B.

I feel like I'm really close - I've been looking at this for too long:

<style>
   #aItems li, h3.bTitle{ cursor: pointer;}

   /* shell - structure */
   #wrap { width:870px; margin:0 auto;}
   #leftcolumn { width: 250px; float: left; margin-right: 30px;    }
   #rightcolumn { width: 590px; float: right;}

   /* Indicators */
   .activeAye{color:blue;}
   .beeOpen{color:red;}

   /* Start Hidden */
   .bItem { display: none;}
</style>
<script>  
    jQuery( document ).ready(function( $ ) {
      /* Column A*/
        /* Click Item  A -> Expand Relevant B's */
        $('.aItem').click(function(){          
          $(this).toggleClass('activeAye');
          $('.aItem').not(this).removeClass('activeAye');

            // Define target B's
            var beeTarget = $(this).data('bdesc');

            // Toggle Targets
            $(beeTarget).slideToggle("medium").prev('h3').toggleClass('beeOpen');
        });
      /* Column B */
        $(".bTitle").click(function(){
            // toggle bItem div open/close
            $(this).next('.bItem').slideToggle("medium");
        });
    });
  </script>

  <div id="wrap">
    <h1>Overlapping Div Sets</h1>
    <ul>
        <li>Item in Column A toggle open/close relevant descriptions on the items in column B.</li>
        <li>Clicking on another Item in A should: 
            <ul>
                <li>Close non-relevant B Items</li>
                <li>Keep open any relevant ones</li>
                <li>Open any that are closed</li>
            </ul>
        </li>
        <li>Clicking any Item in B directly will toggle it open/closed - with no impact to A->B functionality</li>
    </ul>
    <div id="leftcolumn">
      <h4>Column A</h4>
          <ul id="aItems">
            <li class="aItem ayeOne" data-bdesc=".beeOne"><h3>A One</h3>Toggle B1</li>
            <li class="aItem ayeTwo" data-bdesc=".beeOne, .beeTwo"><h3>A Two</h3>Toggle B1 and B2</li>
            <li class="aItem ayeThree" data-bdesc=".beeOne, .beeThree"><h3>A Three</h3>Toggle B1 and B3</li>
            <li class="aItem ayeFour" data-bdesc=".beeFour"><h3>A Four</h3>Toggle B4</li>
            <li class="aItem ayeFive" data-bdesc=".beeFive"><h3>A Five</h3>Toggle B5</li>
            <li class="aItem ayeSix" data-bdesc=".beeSix"><h3>A Six</h3>Toggle B6</li>
          </ul>
    </div><!-- /#leftcolumn -->
    <div id="rightcolumn">
      <h4>Column B</h4>
        <h3 class="bTitle">B One</h3>
        <div class="bItem beeOne">Nam at tortor in tellus interdum sagittis.</div>
        <h3 class="bTitle">B Two</h3>
        <div class="bItem beeTwo">In hac habitasse platea dictumst.</div>
        <h3 class="bTitle">B Three</h3>
        <div class="bItem beeThree">Cras dapibus.</div>
        <h3 class="bTitle">B Four</h3>
        <div class="bItem beeFour">Suspendisse eu ligula.</div>
        <h3 class="bTitle">B Five</h3>
        <div class="bItem beeFive">Sed hendrerit.</div>
        <h3 class="bTitle">B Six</h3>
        <div class="bItem beeSix">Aenean imperdiet.</div>
    </div><!-- /#rightcolumn -->
  </div><!-- /#wrap -->

http://jsfiddle.net/dwcouch/6p65ea2g/

Answer №1

Kindly review the following:

/* Discussion A*/
/* When Item A is Clicked - Expand Related Items B */
$('.aItem').click(function(){    

    $(this).addClass('activeAye');
    $('.aItem').not(this).removeClass('activeAye');
    $('.bItem').prev('h3').removeClass('beeOpen');

    // $('.bItem').slideUp("fast");

    // Select Target Items B
    var beeTarget = $(this).data('bdesc');
    $('.bItem').not( $(beeTarget)).slideUp();
    // Toggle Targets
    $(beeTarget).slideDown("medium").prev('h3').addClass('beeOpen');

});
/* Discussion B */
$(".bTitle").click(function(){
    // toggle bItem div open/close
    $(this).next('.bItem').slideToggle("medium");
});

http://jsfiddle.net/6p65ea2g/1/

Answer №2

After receiving guidance from PaperTank, I made changes to the jQuery code to improve the functionality of clicking on items in Column A. By removing the slideToggle logic and implementing an if statement, I was able to prevent active items in Column A from becoming inactive or closing their corresponding items in Column B.

Although there may be a more elegant solution, this modification serves my current needs. Many thanks to PaperTank for the assistance.

  /* Column A*/
    /* Click Item  A -> Expand Relevant B's */
    $('.aItem').click(function(){
      var beeTarget = $(this).data('bdesc');

      // If A is active, close it's B's and remove active class on A & it's B's
      if( $(this).hasClass('activeAye') ){
          $(beeTarget).slideUp("medium").prev('h3').removeClass('beeOpen');
          $(this).removeClass('activeAye');
      }else{
      // if A is not active:
          // add active class, remove it from others   
          $(this).addClass('activeAye');
          $('.aItem').not(this).removeClass('activeAye');

          //  remove active class from all B's and close them
          $('.bItem').prev('h3').removeClass('beeOpen');
          $('.bItem').not( $(beeTarget)).slideUp();

          // Open A's targets and add active class
          $(beeTarget).slideDown("medium").prev('h3').addClass('beeOpen');
      }
    });

  /* Column B */
    $(".bTitle").click(function(){
        // toggle bItem div open/close
        $(this).next('.bItem').slideToggle("medium");
    });

http://jsfiddle.net/dwcouch/bzum70L4/

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

Combining two table headers into one table and organizing it for a clean appearance

Is it possible to use two different <thead>'s in the same table but have them stacked neatly? Currently, the first heading has 1 fewer column than the second one, resulting in a slightly awkward appearance. If there is a way to extend that first ...

Error: Attempted to export 'e', however it was not defined in the module (located at vite.js?v=d59cec13:236:3) - occurring in the three.js/vite combination

After dabbling in javascript, I decided to explore three.js and found it quite intriguing. However, after hours of setting everything up, I encountered a roadblock. When I attempted to create geometry and render it, the code stopped working. Upon investiga ...

Errors in AJAX calls can sometimes result in an "ERR_EMPTY_RESPONSE" being

I'm currently working on a small CMS/Social network project for a school, which is quite complex and heavily relies on AJAX technology. Randomly, I encounter issues where calls are blocked and the browser displays an error message like net :: ERR_EMPT ...

CSS Styled Product Index

Currently, I am working on creating a product catalog using React and CSS. Everything is going smoothly except for the last row of products. The issue with the last row is that it only contains 1 element, and due to the flex-grow: 1 setting, it ends up ta ...

What is the best way to save an integer in HTML's localStorage instead of a string?

I've encountered an issue while using the localStorage feature in a game I'm developing. Specifically, the money variable should be increasing by 1 every second. Here's a snippet of my code: var money = 0; window.onload = function () { ...

What is the best way to use pattern matching to specifically match IDs while ensuring that the variable number aligns without needing to manually code every potential option?

I have recently acquainted myself with Jquery selectors and they are proving to be very useful. The issue I am facing currently is that all of my variable names follow similar patterns of starting and ending. The IDs are generated from elsewhere, and I am ...

What is the best method for transferring data from an input type="file" to the controller?

Within the ftl: <input type="file" id="doc6" name="documente"> in the JavaScript file: var lx = $("#longX").val(); var ly = $("#latY").val(); var jud = $("#judetPunctLucru").val(); var doc6Type = $("#doc6Type").val(); var doc6 = $('doc6' ...

Navigating a jQuery collection using iteration

My goal is to loop through an array and set values to an element in the following manner: <tool>hammer</tool> var tools = ["screwdriver", "wrench", "saw"]; var i; for (i=0; i < tools.length; ++i){ $("tool").delay(300).fadeOut().delay(100). ...

<dt> and <dd> have not been added after the previous element

I can't seem to figure out why the dt and dd elements are not being added to the dl I created. Here's my initial attempt: // Dictionary list var words = [ { term: "Procrastination", definition: "Pathological tendency to s ...

Issue with a "hover" effect on a specific input[type="submit"] button

I'm having trouble getting my CSS styles to apply correctly to the input field. Can anyone help me understand why this is happening? If you'd like to take a look at the code, here are the links to the .html file and the .CSS styles. The goal is ...

Trouble linking HTML, Javascript, and CSS - seeking help to get them working properly

Hey there! I'm currently trying to transfer my project from Codepen at here to repl.it (This project) which you can find at this link. Don't forget to click run after checking it out! The code is working perfectly fine on Brackets with the same ...

In my attempt to position Font Awesome icons alongside a button icon and create equal spacing between them, I want to achieve the layout displayed in the example

How can I align Social Icons using Font Awesome like in the example provided below? I've tried targeting the Icons but I can't seem to adjust the padding or margin. What am I overlooking? - EXAMPLE <!--BOOTSTRAP--> <link rel="styles ...

Issue of scrolling on Firefox 3.6 due to CSS page width set to 100%

Strange issue with my website on Firefox 3.6 - there is an unwanted horizontal scroll bar at the bottom even though nothing exceeds 100% of the body width. This problem does not occur in Chrome, Safari, or Firefox 4... Any suggestions? Check out the li ...

CSS Word Break and Word Wrap functionality appears to be malfunctioning

Can someone please assist me with an issue I am facing? The word wrap or word break functionality is not working on my string. Here are the details: The company has seen a steady increase in revenue over the past five years, with a total growth of 49% bet ...

Using AngularJS to load a custom JavaScript file within an ng-view

In my sample project, I have utilized Angular Js for the front-end. I have developed a template and implemented dynamic loading of views based on requirements. For this application, I am utilizing angular, jquery, and cusotm js. The structure of my templat ...

Ways to transfer data to a different PHP file without the need to navigate to the actual page

How can I make a button send information to another PHP folder while staying on the same page? <button class="btn btn-outline-dark w-60"><?php echo "<td> <a href='carrinho.php?acao=adc&id=$PegaID'>Adicionar ...

Are external JavaScript files cached in the same manner as images?

Is it possible for a single pagehandler script to be called from the browser cache when navigating between multiple pages that refer to it? ...

Can hidden input forms be used safely for storing comment IDs?

I'm currently working on a project that involves creating a wall similar to Facebook's. I have a question about whether it is safe to use a hidden input field to store the stream id. In my database for comments, I have 4 fields - comment id, str ...

Customize stepper background color in Angular Material based on specific conditions

I am working on a project using Angular Material and I want to dynamically change the color of the stepper based on different states. For example: state: OK (should be green) state: REFUSED (should be red) Here is what I have done so far: <mat-horizo ...

Turn off jQuery for mobile devices

I need assistance in modifying a script that causes a fade effect on certain elements only on desktop and not on mobile devices. I have attempted using the code below, but it seems to hide all elements on all screen resolutions. In my CSS, I am applying ...