Concealing categories within an accordion-styled menu

Recently, I put together a list that includes various pieces of information along with an accordion menu.

Take a look at the list

However, I've encountered a small issue which has left me quite perplexed. When a menu item is clicked - for instance, the animal menu - its corresponding information appears as expected.

My confusion arises when, after viewing the details under one menu, if the user proceeds to click on another menu, such as colors, the previous menu remains open alongside the new one. Ideally, I would like each menu click to close any previously opened menus and display only the content of the selected menu.

Thank you in advance for assisting me in resolving this dilemma.

'use strict';


    // search & highlight

    ;( function( $, window, document, undefined )
    {
        var $container = $( '.faq' );
        if( !$container.length ) return true;

        var $input          = $container.find( 'input' ),
            $notfound       = $container.find( '.faq__notfound' ),
            $items          = $container.find( '> ul > li' ),
            $item           = $(),
            itemsIndexed    = [];

        $items.each( function()
        {
            itemsIndexed.push( $( this ).text().replace( /\s{2,}/g, ' ' ).toLowerCase() );
        });

        $input.on( 'keyup', function( e )
        {
            if( e.keyCode == 13 ) // enter
            {
                $input.trigger( 'blur' );
                return true;
            }

            $items.each( function()
            {
                $item = $( this );
                $item.html( $item.html().replace( /<span class="highlight">([^<]+)<\/span>/gi, '$1' ) );
            });

            var searchVal = $.trim( $input.val() ).toLowerCase();
            if( searchVal.length )
            {
                for( var i in itemsIndexed )
                {
                    $item = $items.eq( i );
                    if( itemsIndexed[ i ].indexOf( searchVal ) != -1 )
                        $item.removeClass( 'is-hidden' ).html( $item.html().replace( new RegExp( searchVal+'(?!([^<]+)?>)', 'gi' ), '<span class="highlight">>$&</span>' ) );
                    else
                        $item.addClass( 'is-hidden' );
                }
            }
            else $items.removeClass( 'is-hidden' );

            $notfound.toggleClass( 'is-visible', $items.not( '.is-hidden' ).length == 0 );
        });
    })( jQuery, window, document );


    // toggling items on title press

    ;( function( $, window, document, undefined )
    {
        $( document ).on( 'click', '.faq h2 a', function( e )
        {
            e.preventDefault();
            $( this ).parents( 'li' ).toggleClass( 'is-active' );
        });
    })( jQuery, window, document );


    // auto-show item content when show results reduces to single

    ;( function( $, window, document, undefined )
    {
        var $container = $( '.faq' );
        if( !$container.length ) return true;

        var $input      = $container.find( 'input' ),
            $items      = $container.find( '> ul > li' ),
            $item       = $();

        $input.on( 'keyup', function()
        {
            $item = $items.not( '.is-hidden' );
            if( $item.length == 1 )
                $item.addClass( 'js--autoshown is-active' );
            else
                $items.filter( '.js--autoshown' ).removeClass( 'js--autoshown is-active' );
        });
    })( jQuery, window, document );
body {
  font-family: Roboto, sans-serif;
  color: #34434b;
  background-color: #fff;
  padding: 5rem 1.25rem;
  direction: rtl;
  text-align: right;
  /* 80 20 */
}

a {
  color: #468FB3;
  text-decoration: none;
}
a:hover {
  text-decoration: underline;
}

.container {
  width: 100%;
  max-width: 640px;
  /* 960 */
  margin: 0 auto;
}
.container h1 {
  font-size: 42px;
  font-weight: 300;
  color: #5594b3;
  margin-bottom: 40px;
}
.container h1 a:hover, .container h1 a:focus {
  color: #a664b7;
}
.container p {
  line-height: 1.6;
}

.faq input {
  width: 100%;
  height: 60px;
  font-size: 20px;
  background-color: #fff;
  box-shadow: 0px 2px 4px rgba(52, 67, 75, 0.2);
  display: block;
  padding: 0 20px;
  margin-bottom: 40px;
  -webkit-transition: box-shadow .1s linear;
  transition: box-shadow .1s linear;
}
.faq input::-webkit-input-placeholder, .faq input::-moz-placeholder, .faq input:-ms-input-placeholder {
  color: #a1bdcb !important;
}
.faq input:focus {
  box-shadow: 0px 4px 8px rgba(52, 67, 75, 0.4);
}
.faq .highlight {
  background-color: #f00d77;
}
.faq > ul > li:not(:first-child) {
  border-top: 1px solid #dcebed;
  margin-top: 20px;
  padding-top: 20px;
}
.faq > ul > li.is-hidden {
  display: none;
}
.faq > ul > li h2 {
  font-size: 24px;
  font-weight: 700;
}
.faq > ul > li h2:hover, .faq > ul > li h2:focus {
  color: #a664b7;
}
.faq > ul > li.is-active h2, .faq > ul > li:target h2 {
  color: #a664b7;
}
.faq > ul > li > div {
  display: none;
}
.faq > ul > li.is-active > div, .faq > ul > li:target > div {
  display: block;
  margin-top: 10px;
}

.faq__notfound {
  font-size: 20px;
  font-style: italic;
  display: none;
}
.faq__notfound.is-visible {
  display: block;
}

.container footer {
  color: #a1bdcb;
  margin-top: 40px;
}
.container footer a:hover, .container footer a:focus {
  color: #5594b3;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- partial:index.partial.html -->
<div class="container" role="main">

    <h1>LIST</h1>

    <div class="faq">
        <input type="search" value="" placeholder="Type some keywords" />
        <ul>
            <li id="faq-1">
                <h2><a href="#faq-1">Animals</a></h2>
                <div>
                    <p>
                        cat <br>
                        dog <br>
                        lion <br>
                        tiger <br>
                    </p>
                </div>
            </li>
            <li id="faq-2">
                <h2><a href="#faq-2">Names</a></h2>
                <div>
                    <p>
                        jim <br>
                        jack <br>
                        mary <br>
                        tom <br>
                    </p>
                
                </div>
            </li>
            <li id="faq-3">
                <h2><a href="#faq-3">colors</a></h2>
                <div>
                    <p>
                        blue <br>
                        red <br>
                    </p>
                
                </div>
            </li>
            
        </ul>
        <div class="faq__notfound"><p>No matches were found&hellip; Try &ldquo;giza&rdquo;.</p></div>
    </div>

    <footer><p></p></footer>
</div>
<!-- partial -->
<script src='./jquery.min.js'></script><script  src="./script.js"></script>

Answer №1

Check out this simplified code snippet

$('.faq h2 a').on('click', function(e){
    e.preventDefault();
    $(this).parents('li').toggleClass('is-active').siblings().removeClass('is-active');
});

Don't forget to clean up your CSS by removing unnecessary styles like :target

.faq > ul > li.is-active h2 {
  color: #a664b7;
}

.faq > ul > li.is-active > div {
  display: block;
  margin-top: 10px;
}

Here is the updated code : https://codepen.io/vinodmurukesan/pen/zYrMqyJ

Answer №2

Here is a helpful function code snippet

;( function( $, window, document, undefined )
{   
    $( document ).on( 'click', '.faq h2 a', function( e )
    {
        e.preventDefault();
        var refId = $(this).parents('li').attr('id'); 
          
        $('li').each(function(){
          if(refId != $(this).attr('id')){

          $( this ).removeClass('is-active');   
          }
        });
        $( this ).parents( 'li' ).toggleClass( 'is-active' );
    });
})( jQuery, window, document );

Answer №3

If you swap out this particular function in your script.js file starting at line 57, get ready for some astonishing results.

;( function( $, window, document, undefined )
    {
        $( document ).on( 'click', '.faq h2 a', function( e )
        {
            e.preventDefault();
            $('li').each(function(){

              $( this ).removeClass('is-active');   
            });
            $( this ).parents( 'li' ).toggleClass( 'is-active' );
        });
    })( jQuery, window, document );

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

What advantages does utilizing an angular directive provide in the context of a comment?

Up to now, I have primarily used Directives in the form of Elements or Attributes. Is the Comment style directive simply a matter of personal preference for style? app.directive('heading', [function () { return { replace: true, ...

Injecting AngularJS directives and styling elements into the body section of a Twig template using the {% block body %} tag

I'm currently in the process of constructing a Rest API using Symfony 3 and Fosresbundle, with AngularJS responsible for fetching JSON data within twig templates. However, I've encountered an issue where I need to specify angularJS directives an ...

Showcasing the information stored within my li element, I am able to access and view the data through my console

I want to showcase the data in the browser Upon hitting the api call, I retrieve the data in my console. The challenge lies in displaying the data within my li tag. Below are snippets of my relevant code and the entire code can be found in the gist links p ...

Why is 'this.contains' not recognized as a function when I invoke it within another function?

While attempting to create a Graph and incorporating one method at a time, I encountered an issue. Specifically, after calling a.contains("cats"), I received the error '//TypeError: Cannot read property 'length' of undefined'. Could thi ...

When hovering, transition occurs unless the cursor is over a specific element

I have created a small box element with a close button that looks like this: ___ | X| ‾‾‾ In order to make it more interactive, I applied some CSS so that when hovered, the box expands like this: ___________________ | X| ‾ ...

Looking to organize my divs by data attributes when clicked - how can I achieve this with javascript?

I am looking to implement a dropdown sorting functionality for multiple divs based on different data attributes such as price and popularity. The specific divs are labeled as "element-1" and are contained within the "board-container". var divList = $(". ...

Verify that the select field has been chosen using Protractor

Currently, I am in the process of developing a test that places importance on whether a select field has already been populated. it('should automatically select a field if it hasn't been selected previously', function() { var usersField = ...

Sign up for a Jquery template event

When utilizing a jquery template, the following HTML markup is being used: <div id="results"> <div class="CommentItem" commentid="33064" id="33064" data-guid="/Profile/Profile.aspx?id=Charliedog33"> <div class="CommentPic" ...

Exploring the differences between Zurb Foundation 6's app.scss and _settings.scss files

Can you explain the distinction between app.scss and _settings.scss when using Zurb Foundation 6? ...

There are no documents found with the specified UUID in MongoDB

I have been attempting to retrieve a specific document from MongoDB that includes the field "ownerId" containing a binary UUID. In the Mongo console, when I run the command db.dataset.find({ownerId: BinData(3,"ZQ6EAOKbQdSnFkRmVUUAAA==")}).pretty() The ou ...

What are the most effective techniques for utilizing JavaScript modules in both the Server and Browser environments?

Currently, I am in the process of developing a JavaScript project that utilizes NodeJS. There are certain objects that need to be shared between the client and server side. I attempted to employ the module system in Node, but struggled to find an appropria ...

Re-activate video playback after 30 seconds of user inactivity (using RxJs)

My intention is to provide a brief explanation of the functionality I am looking for. Essentially, when a video is playing, I want it to pause if a user clicks on it, allowing them to do something else. Then, after 30 seconds of idle time, I need the video ...

Retrieve all findings related to an ongoing loop update issue within react-table

Check out this Playground Sandbox where custom hooks for react-table have been set up to allow for customized search and row selection features. However, after selecting a single row, some unexpected behavior occurs, including the select All option not f ...

IE is failing to display the textarea, but it is successfully getting submitted

I've written a function in jQuery and JavaScript that generates a form element: createEmail: function(title){ var $emailForm = $('<form>',{action: 'sendEmail.php', id: 'emailForm'}); var $table = $( ...

Problem with Jquery Sticky Navigation

I've been struggling to understand this issue and can't seem to find any help. http://fiddle.jshell.net/DQgkE/7/show/ The user experience is currently a bit glitchy, but what I would like is: 1) When scrolling down the page, I want the Sticky ...

Select checkboxes by clicking a button that matches the beginning of a string in JavaScript

I have a form with a list of users and checkboxes below their names. Each user has a button that should select all checkboxes assigned to them. Below is the code for the dynamically created buttons and checkboxes. The included function takes the form name ...

Utilizing slug URLs effectively in Next.js

In my current project with Next.js, I am working on implementing "dynamic routes". The goal is to update the URL structure such that upon clicking, the URL should look like "myurl.com/article/55". To achieve this, I have utilized the following "link tag": ...

I need help figuring out how to choose an option from a drop-down menu that has a dynamically changing id every

When using Selenium Webdriver, I am trying to select the "802.11n" option from a drop-down menu where the "sbSelector_xxx" id changes each time the page is reloaded. <div id="RADIO_5GHz_adv" style="display: block;"> <table class="block" border="0 ...

Using VBA and Selenium to access iframes within HTML with the #document tag

I am currently facing a challenge in accessing the HTML content within two iframes using Selenium Basic in VBA. Due to restrictions on our machines, we are unable to use IE and other tools like Python are not available to us. In the past, I was able to ac ...

XMLHttpRequest response: the connection has been terminated

After developing a Flickr search engine, I encountered an issue where the call to the public feed or FlickrApi varies depending on the selection made in a drop-down box. The JSONP function calls provide examples of the returned data: a) jsonFlickrApi({"ph ...