The collapsible section in CSS/Javascript remains open and does not close

I am currently working on collapsible sections that should open and close when clicked, but unfortunately they are not closing once opened.

You can view the use case here: Use case

This is the code I am using:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  $(document).ready(function(){
  $('.markdown-block .sqs-block-content h3').addClass('ui-closed').css('cursor','pointer');
  $('.markdown-block .sqs-block-content h3').css('cursor','pointer');
  $(".markdown-block .sqs-block-content h3").nextUntil("h3").slideToggle();
  $(".markdown-block .sqs-block-content h3").click(function() {
    $(".markdown-block .sqs-block-content h3").nextUntil("h3").slideUp();
    $(".markdown-block .sqs-block-content h3").removeClass('ui-open');
    $(".markdown-block .sqs-block-content h3").addClass('ui-closed');
$(this).nextUntil("h3").slideDown();
    $(this).toggleClass('ui-closed ui-open');
  });
});
</script>

Can anyone help me modify this code so that the sections collapse after being opened?

Answer №1

The issue at hand stems from the absence of a conditional check to determine when to toggle between open and closed states. Currently, each click triggers all actions simultaneously, resulting in both opening and closing operations occurring together. The slideDown function appears to work initially because it is the last action executed. However, attempting to close the element will invariably cause it to reopen due to the subsequent call to slideDown. To resolve this, implementing an IF statement and segregating the behavior will enable elements to expand or collapse based on their current class assignments.

Consider the following revised script for a solution:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script>
      $(document).ready(function(){
      $('.markdown-block .sqs-block-content h3').addClass('ui-closed').css('cursor','pointer');
      $(".markdown-block .sqs-block-content h3").nextUntil("h3").slideToggle();
      $(".markdown-block .sqs-block-content h3").click(function() {

        if ( $(this).hasClass('ui-open')) {
          $(".markdown-block .sqs-block-content h3").nextUntil("h3").slideUp();
          $(".markdown-block .sqs-block-content h3").removeClass('ui-open').addClass('ui-closed');
        } else {
          $(".markdown-block .sqs-block-content h3").nextUntil("h3").slideDown();
          $(".markdown-block .sqs-block-content h3").removeClass('ui-closed').addClass('ui-open');
        }
      });
    });
    </script>

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 is the best way to send a response with multiple parts in ExpressJS?

My application showcases a collection of images along with their respective titles and descriptions. As the app communicates with the node server via a get request, I am seeking guidance on how to have the server respond with both the images and their as ...

Attaching a JQuery Event to a Custom Control on Google Maps

Struggling to enhance Google Maps with custom controls using CSS and JQuery. The documentation doesn't seem to address the issue I'm facing. Check out the markup, styling, and JQuery here. Following the instructions in the documentation, I adde ...

Orders in WooCommerce are being mysteriously created with no information provided and stuck in a pending payment state

Are you experiencing the issue of blank orders being generated in WooCommerce with no details and a pending payment status? I am utilizing the WooCommerce plugin along with the Elavon payment gateway, and although everything seems to be set up correctly, t ...

Retrieve the array from MongoDB based on a specific property

The data stored in my MongoDB collection is structured as follows: [ { "_id": "1", "name": "X", "age": "2", "createdAt": "2020-02-29T22:22:49.491Z", "updatedAt": "2020-02-29T22:22:49.491Z", "__v": 0 ...

The symbol '★' represents the '★' content in CSS

Here is the CSS code I am using: .rating:not(:checked) > label:before { content: '★'; } However, when it is displayed on the screen, instead of seeing a ★, I see â˜. It's strange because if I use Firebug and manually change the ...

Microsoft Edge introduces an unexpected parameter to the URL

Unusual parameter ?zx=djlj8eui511x appearing in URL after clicking <a [href]="navItem.url" *ngIf="navItem.index <= wizardConfiguration.activeTab.index" class="rktn-wizard-navigation-container_passed-item" ...

What is the best way to handle escape characters in a string in JavaScript?

Within a file named file-a.php, I have created a custom shortcode that generates the following simplified HTML structure: <div><a href="#"><span>Link text</span></a></div> In another file, file-b.php, I retrieve the [s ...

What is the best way to convert a block of text to a string, especially if it contains quotation marks?

Is there a way to turn text into a string even if it contains quotes that could potentially cause issues with validation? How can I create a valid string when the text includes quotations? ...

refresh content during page transitions on Symfony 3

I've been tackling a challenge in my Symfony app where I need to transition from the script to the form without causing any page refreshes. https://i.sstatic.net/xUtA2.png To prevent the main layout (with both script and form) from reloading, I impl ...

What is the best way to ensure my <h5> element fits perfectly inside its parent div vertically?

Currently facing an issue with finding a solution to my problem. The challenge involves having a header tag nested within multiple divs. Below is the structure: <div class="card"> <div class="layout-left"> <div class="card-header"> ...

Transforming the JSON data into a text format

I have a JSON object structured like this: { "name": "ok", "country": "US", "phone": "900", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f70745f727e767331707c">[email protected]</a>", ...

The enigmatic borders of a website

While working on a custom Wordpress theme, I encountered an issue where the entire body of the page was slightly pushed down. Using Chrome's inspector tool, I identified the following problematic styles: <style type="text/css" media="screen> ...

Check whether the username variable is blank; if it is, then refrain from navigating to page2.php

Introducing meekochat, a live chat website where users can connect with others. To get started, simply input your name on page1.php and you'll be directed to page2.php for chatting. However, I have implemented a feature in my code to ensure that if th ...

Combining objects using ES6 import/export with async/await functionality

I am facing a situation where I have two files named config.js and config.json and my goal is to combine them into one object and then export it: config.json { "c": 3 } config.js import fs from "fs"; import fse from "fs-extra& ...

Performing ad-hoc queries on a Postgresql database using Node.js and Express to manipulate row data

I am faced with a challenge of selecting one entry randomly from a table containing 46 entries, and then passing the data from that particular query to my handlebars files. I am unsure about how to approach the task of randomly querying the database and re ...

What is the best way to flatten a nested array of objects with lodash?

I'm trying to convert a JSON object into a different format using JavaScript and lodash: { "BidNumber": 2, "BidResult": 1, "BidAmount": "6756", "BidData": [ { "name": "JonSnow", "Data": "Standard data f ...

Generate a dynamic dropdown menu in PHP that updates in real-time on the webpage

Seeking assistance in populating a drop-down menu with values from a database on the same page as the input field. I have explored various options on forums without success. Upon hitting submit, the page redirects to a blank page. Even after attempting ...

Updating React state by changing the value of a specific key

I've been diving into React lately and I'm facing an issue with updating state values for a specific key. Below is my current state: this.state = { connections : { facebook : "http://facebook.com", flickr : null, ...

Revamp MUI class names with React Material UI's innovative randomization and elimination

Can names be randomized or Mui-classNames removed? https://i.stack.imgur.com/J6A9V.png Similar to the image displayed? (All CSS class names would be jssXXX) Appreciate your assistance. ...

Point the direction to nextjs and react native expo web

I am currently working on redirecting a URL to another within my website, specifically in Next.js and Expo React Native Web. While I don't have an actual "About" page, I do have other pages nested under the "about" folder and am aiming to direct any ...