Questions and Answers - Expand/Collapse Feature for Accordions

I am currently working on enhancing an existing "FAQ" accordion page by implementing the expand/collapse feature to function seamlessly. I have successfully set up the page to begin with all sections collapsed, however, I am facing an issue where clicking on one section to expand it does not collapse the previously expanded section.

It is crucial for me to maintain the search functionality as it is.

$('.collapse').collapse(); // Ensure all sections are collapsed initially

// The following code snippet enables the search functionality.
(function() {
  var searchTerm, panelContainerId;
  $('#accordion_search_bar').on('change keyup', function() {
    searchTerm = $(this).val();
    $('#accordion > .panel').each(function() {
      panelContainerId = '#' + $(this).attr('id');

      // Making the search case-insensitive
      $.extend($.expr[':'], {
        'contains': function(elem, i, match, array) {
          return (elem.textContent || elem.innerText || '').toLowerCase()
            .indexOf((match[3] || "").toLowerCase()) >= 0;
        }
      });

      // End of making search case-insensitive

      // Show and Hide triggers based on search input
      $(panelContainerId + ':not(:contains(' + searchTerm + '))').hide(); //Hide rows that do not contain the search query.
      $(panelContainerId + ':contains(' + searchTerm + ')').show(); //Show rows that match the search query.

    });
  });
}());
@import url('https://fonts.googleapis.com/css?family=Anton');
body {
  background: #29AB87;
  background-color: green;
}

h1 {
  font-family: 'Anton', sans-serif;
  color: #29AB87;
}
/* CSS styles continue... */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet'>
<link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css' rel='stylesheet'>
<link href="css/style.css" rel="stylesheet">

<body>
<!-- HTML content continues... -->

The current behavior is such that all items start off collapsed, but when a user clicks on a paw icon to expand, the previously expanded item should collapse automatically. This can be achieved by toggling the collapse state of each item.

Access Original Source on Codepen

Answer №1

If you prefer the panels to initially be collapsed, avoid using the in class.

When you call $('.collapse').collapse();, it doesn't collapse your panels; instead, it reactivates the .collapse elements with the default options. This overrides .in (closing the panels) and data-parent (eliminating one-panel-at-a-time functionality).

You don't need to repeat the :contains pseudo-selector three times on each keypress. One instance is sufficient. Also, there's no need to manually iterate over all #accordion's .panels; a broader selector will suffice.

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

Is it possible to pass the image source to a Vue.js component through a

I am encountering an issue while trying to display an image in the designated location within display.vue. Even though {{ someText }} returns the correct file path (../assets/city.png), the image is not being output correctly. Here is how my code looks: ...

Unexpected 404 Error in Node.JS Express following a POST submission

I've recently built my first application using Express and MySQL. I'm encountering an issue with saving data in my database - every time I make POST requests, I receive a status 404 error and nothing beyond that. This roadblock is preventing me f ...

Convert JQuery to a click event

I have a code snippet that is currently functioning properly $(window).load(function(){ $(document).ready(function(){ $("input[name ='_sft_product_cat[]']").parent().next(".children").css("background", "yellow"); }) }); My goal is to convert th ...

The module './installers/setupEvents' could not be located within Electron-Winstaller

After encountering an error while attempting to package my Angular app on Windows 10, I'm looking for help in resolving the issue: https://i.stack.imgur.com/yByZf.jpg The command I am using is: "package-win": "electron-packager . qlocktwo-app --ove ...

Can you identify the missing piece in my design?

#container { width: 250px; margin: 0 auto; } .group { border: 1px solid grey; margin-bottom: 20px; } .group p { text-align: center; font-family: Helvetica sans-serif; font-size: 25px; color: #2e3d49; } .group img{ wid ...

Save to clipboard without the use of Flash technology

In my search for a way to copy text to the clipboard, I have come across many solutions that either rely on flash or are designed for websites only. I am in need of a method that can copy to the clipboard automatically without flash, specifically for use ...

Troubleshooting Issues with JavaScript Counter and JSON Integration

When manually inserting a number into the HTML, the counter works fine. However, when pulling data remotely, there seems to be a problem. The remote data is logging correctly in the console and appears properly in the DOM element when the counter code is d ...

Different body background color changes every second

I have a function called makeRandColor that generates a random color using RGB and template string literals. However, I am struggling to figure out how to make it work every second. I tried using setInterval but it doesn't seem to be functioning prope ...

Ways to transfer information from the server to the user interface in a WordPress extension

I am currently developing a WordPress plugin and have successfully created a form in the admin panel. Now, I am looking to transfer the data collected from that form to my Frontend JavaScript file. Is there a way to achieve this, and if so, what steps shou ...

Scripts added to the layout page are not functioning correctly in ASP.NET MVC 5

During the development of my ASP.NET project, I encountered an issue where scripts that were placed in the "Head" section of my layout page were not accessible for use in the rendered view. The code snippet from my layout page looks like this: <!DOCT ...

Unable to find 'react/lib/merge' module

I'm currently working on a React project and utilizing Babel and Webpack. Within one of my files, I have this require statement: var merge = require('react/lib/merge'); Unfortunately, I'm encountering the following error: ERROR in . ...

Ensuring uniformity in picture size while uploading images in Angular by resizing and including white borders

Currently, I am working with pictograms and I am looking to showcase all the pictograms that the user has in both grid list and grid tiles formats. However, the challenge lies in the fact that the aspect ratio of the pictograms varies significantly depen ...

How can I remove the script from Response.Write?

Instead of using Response.Write to test some values in code with an alert box, I tried writing dynamic javascript directly into the page. Even after reverting the code, rebuilding, and clearing all temp data from IE, the alert still pops up. I followed a ...

Add a button feature to both upload and download a todo list within a JavaScript file, similar to a text file

I'm looking to enhance my simple todo list with a download and upload function. I want to be able to save the list in local storage and then upload or download it from a server code. Below is a link to my code: https://jsfiddle.net/zahrashokri/uqkn6t ...

The Material multi select is unable to show the chosen name values at this time

I'm utilizing the Material Multiple select feature to pick employees, and you can see it in action on this demo: sandbox demo However, instead of displaying the ID values of the selected employees, I want to display their names. To achieve this, I t ...

Using Three.js to incorporate an external JavaScript file into an HTML document

Currently experimenting with three.js and successfully rendered a 3D cube using HTML. Here's a snippet of the HTML code: <div id="render" class="center-block"> <script> // JavaScript code for rendering the 3D cube goes here </script&g ...

Tips for organizing parallel arrays with the provided data

I am having trouble with this question as it seems a bit vague to me. The concept appears more challenging than what we learned in class, and I'm not sure where to start. If someone could provide a simplified explanation, I would greatly appreciate it ...

What is the best way to enable visitors to share the current page on blogger, similar to the functionality of Facebook's

I'm looking to integrate a button on my website similar to Facebook's like button that allows users to share my site on Blogger. However, after checking Blogger's developer site, it appears that there is no equivalent JavaScript code availab ...

Issue with Achieving Two-Way Binding in Angular 1.5 Component when using $ctrl

I am struggling with customizing some products using a component in my index.html. Ultimately, I need to calculate the total of selected products within the main controller "planosVoz" using two-way binding on the svaTotal property in the component control ...

What's the reason popstate does not trigger in Safari during the loading of an iframe?

When using Safari, I've noticed that if an iframe is loading and the user changes the history state by navigating back or forward, the popstate event doesn't get triggered. This results in the application state being out of sync with the window l ...