Ways to guarantee that only one accordion tab is open at a time while keeping it open continuously

Hey everyone, I'm just starting to learn how to code and still getting the hang of using Stack Overflow so please bear with me if my question isn't perfectly formatted. I have created an accordion that is almost functioning correctly, but I need a bit of help tweaking it. Currently, my accordion has two tabs and when one tab is opened, the other one closes which is working fine. However, I want to make sure that at least one tab is always open, specifically the first one when the page loads. So, if I click on the second tab, the first one should remain open until I explicitly close it by clicking on it again. Right now, both tabs are collapsed on page load and can be closed even if they are already open.

$(document).ready(function() {
  function close_accordion_section() {
    $('.accordion .accordion-section-title').removeClass('active');
    $('.accordion .accordion-section-content').slideUp(300).removeClass('open');
  }

  $('.accordion-section-title').click(function(e) {
    var currentAttrValue = $(this).attr('href');

    if ($(e.target).is('.active')) {
      close_accordion_section();
    } else {
      close_accordion_section();
      $(this).addClass('active');
      $('.accordion ' + currentAttrValue).slideDown(300).addClass('open');
    }

    e.preventDefault();
  });
});
.accordion,
.accordion * {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

.accordion {
  overflow: hidden;
  border-radius: 5px;
  background: white;
}

.accordion-section-title {
  width: 100%;
  padding: 0px;
  display: inline-block;
  background: #585858;
  transition: all linear 0.15s;
  font-size: 14px;
  color: #F2F2F2;
}

.accordion-section-title.active,
.accordion-section-title:hover {
  background: white;
  text-decoration: none;
  font-weight: bold;
  color: #585858;
}

.accordion-section:last-child .accordion-section-title {
  border-bottom: none;
}

.accordion-section-content {
  padding: 0px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="accordion">
  <div class="accordion-section">
    <a class="accordion-section-title" href="#accordion-1">Accordion Section #1</a>

    <div id="accordion-1" class="accordion-section-content">
      <p>accordion 1 text</p>
    </div>
  </div>
</div>

<div class="accordion">
  <div class="accordion-section">
    <a class="accordion-section-title" href="#accordion-2">Accordion Section #2</a>

    <div id="accordion-2" class="accordion-section-content">
      <p>accordion 2 text</p>
    </div>
  </div>
</div>

Any help would be greatly appreciated. Thank you!

Answer №1

Upon document readiness, add the classes "open" and "active" to the first elements with the classes ".accordion-section-content" and ".accordion-section-title" respectively. Do not execute the function "close_accordion_section()" if the clicked ".accordion-section-title" already has the class "active".

$(document).ready(function () {
    $($('.accordion .accordion-section-title')[0]).addClass('active');
    $($('.accordion .accordion-section-content')[0]).slideDown().addClass('open');

    function close_accordion_section() {
        $('.accordion .accordion-section-title').removeClass('active');
        $('.accordion .accordion-section-content').slideUp(300).removeClass('open');
    }

    $('.accordion-section-title').click(function (e) {
        var currentAttrValue = $(this).attr('href');

        if ($(e.target).is('.active')) {
            //close_accordion_section();
        } else {
            close_accordion_section();
            $(this).addClass('active');
            $('.accordion ' + currentAttrValue).slideDown(300).addClass('open');
        }

        e.preventDefault();
    });
});
.accordion,
.accordion * {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

.accordion {
  overflow: hidden;
  border-radius: 5px;
  background: white;
}

.accordion-section-title {
  width: 100%;
  padding: 0px;
  display: inline-block;
  background: #585858;
  transition: all linear 0.15s;
  font-size: 14px;
  color: #F2F2F2;
}

.accordion-section-title.active,
.accordion-section-title:hover {
  background: white;
  text-decoration: none;
  font-weight: bold;
  color: #585858;
}

.accordion-section:last-child .accordion-section-title {
  border-bottom: none;
}

.accordion-section-content {
  padding: 0px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="accordion">
  <div class="accordion-section">
    <a class="accordion-section-title" href="#accordion-1">Accordion Section #1</a>

    <div id="accordion-1" class="accordion-section-content">
      <p>accordion 1 text</p>
    </div>
  </div>
</div>

<div class="accordion">
  <div class="accordion-section">
    <a class="accordion-section-title" href="#accordion-2">Accordion Section #2</a>

    <div id="accordion-2" class="accordion-section-content">
      <p>accordion 2 text</p>
    </div>
  </div>
</div>

Answer №2

Here is an example of how you can achieve this:

$( ".selector" ).accordion({
  active: 1
});

Alternatively, you can use the following code:

$( ".selector" ).accordion( "option", "active", 1 );

Feel free to replace the number 1 with the accordion panel ID that you want to be active upon page load.

Remember to include this code inside the document.ready function.

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

Ways to include multiple pieces of data in a JQuery Mobile List view

Obtaining JSON data (list of available Hotels within a certain distance) and extracting the following information in JSON format: Name of Hotels, Distance of Hotel from our current location, number of rooms. There might be multiple Hotels within the specif ...

JavaScript salary calculation function not functioning properly

Once the user inputs the employee's name and the number of hours they worked on the HTML form, the submit button captures this information and stores it in variables for calculating their pay. The script also factors in overtime pay. Despite feeling l ...

Interactive user-friendly form with real-time response features

I am currently working on an application form where users need to answer questions, and I am in need of some responsiveness. Specifically, I would like to implement a feature that shows additional fields based on the user's selection. For example, if ...

Guide on positioning an SVG button within a form

I am attempting to design a form with two input fields and a button. Rather than using a plain text button, I prefer to utilize an SVG graphic for the button; however, it is not aligning correctly. Consider the following HTML and CSS: body { backg ...

Guide to displaying a loading image when selecting an item from a dropdown menu using JavaScript

When using three drop-down lists and performing an AJAX call on each dropdown list's onclick function, I encountered a delay in loading the data. To address this issue, I attempted to display a loading image while processing the AJAX call. <form ...

Slide your finger upwards to shut down the mobile navbar in bootstrap

Hey there, I'm currently developing a website using Bootstrap framework v3.3.4. I have a mobile navbar that opens when I click a toggle button, but I would like it to slide up to close the navigation instead. Here is an image showing the issue Do y ...

What causes the transformation of a POST request into a GET request?

Upon utilizing jQuery's $.ajax() or $.post() method to transmit form data to the server, I've noticed that the 'data' string gets appended to the end of the URL. This seems to be causing the POST request to transform into a GET request. ...

Guide on altering the cell's background hue depending on its value through javascript

I'm dealing with a table that has 3 columns: field1 is a Category field2 and field3 contain Measures (specifically integers 1, 2, 3, 4, and 5). Is there a way to use Javascript to conditionally format the background color of cells in the table hol ...

Ensuring the script waits for the complete loading of iframe prior to

I'm faced with an issue on the website I'm currently working on. There's a Live Chat plugin integrated on an iframe, and I need to change an image if no agents are available. Interestingly, my code works perfectly fine when tested on the con ...

Ways to avoid overflow of dynamically added div element?

Currently, I am facing an issue while dynamically appending div elements with the .magnet class to my page. These elements end up overflowing the container boundaries and I am struggling to find a solution for this problem. If anyone could check out my j ...

What could be causing me to receive null when trying to retrieve an element with document.getElementById, even after invoking $(document).ready(function() { ... })?

Here's a small example. I'm feeling a bit rusty with JavaScript, as it's been some time since I last worked with it. The problem I'm encountering is an error in Chrome developer tools: "Uncaught TypeError: Cannot set property 'src ...

Refresh the data in the DataTables table using a fragment

Currently, I am attempting to reload a fragment using ajax. However, after the reload, my event select and row count do not function properly. It seems that the default configuration is not behaving as expected: @PostMapping("/admin/add") ...

Using jQuery AJAX to Populate a Textbox and Dropdown Menu

I am new to using JQuery AJAX, so I am still learning the syntax. Currently, I am retrieving values from a database and populating a dropdown box. What I would like AJAX to do is fill in three other fields with hardcoded information when a selection is mad ...

What is the best way to incorporate text transitions using jquery?

Recently, I've come across this code snippet: $('#slider_title').text(var); This line of code successfully adds the text stored in a variable to the paragraph identified by the id "slider_title". And now, my goal is to smoot ...

Storing extensive dictionaries in Django using PostgreSQL is a common and efficient practice

In order to store a list of airport codes and their corresponding names in a Django PostgreSQL database using models, I have created a dictionary with entries such as: airports = {"JFK": 'New York', "AAE": 'Annabah', "AAF": ...

Zurb's Vertical Navigation Bar: A Stylish and Functional Design

I attempted to replicate the left navigation bar from this link: The responsive navigation bar and contents on the right caught my attention. Currently, I am working on a project that requires a similar navigation bar. While I am proficient in HTML and C ...

Custom Tooltips arrow is not receiving the CSS styling

I have implemented ReactTooltip from the ReactTooltip library You can view an example here Component Setup <ReactTooltip className={styles.customTheme} id={id} place={placement} effect="solid"> {children} </ReactTooltip> Stylin ...

Is it possible for a Simplemodal popup to appear only once per user session

I'm completely new to javascript and jQuery. Recently, I've started using SimpleModal basic from SimpleModal to show a popup upon visitors landing on my website. Everything seems to be working perfectly, but there's one issue - the popup kee ...

What causes my `` to function intermittently?

I've been experimenting with adding attributes and styling to elements. Sometimes my code works perfectly fine, while other times it doesn't produce the desired output. Here's an example of when it works: $('.card-text') .text( ...

Tips for maintaining DataTables filters after navigating Back/Forward or refreshing the page

We are currently utilizing DataTables for our table, and we are encountering difficulties in retaining the history of filters that were previously applied to the table. This would allow users to navigate back and forth and refresh through these filters. O ...