Is the HTML Accordion Panel set to be open by default?

I recently found this amazing animated accordion menu on the W3 Schools website and I really appreciate its design. However, I am struggling to figure out how to set a specific section to be open and "active" by default.

Visit the original page here

I attempted changing the class of the button to "active," but that didn't seem to work as expected. It only changed the "+" sign to a "-" sign without displaying the menu content.

Any suggestions on how to achieve this?

<div id="accordion_menu">
                    <button class="accordion">What You Will Learn</button>
                        <div class="panel scrolled">
                            <ul>
                                <li>Fundamental algorithms for signal processing.</li>
                                <li>Techniques for beam forming.</li>
                                <li>Trade-offs among active waveform designs.</li>
                                <li>Ocean medium effects.</li>
                                <li>Shallow water effects and issues</li>
                                <li>Optimal and adaptive processing</li>
                            </ul>
                        </div>  

                    <button class="accordion">Course Outline</button>
                        <div class="panel">
                            <ol>
                                <li>
                                    <p><em>Introduction to Sonar Signal Processing.</em> Introduction to sonar detection systems and types of signal processing performed in sonar. Correlation processing, Fournier analysis, windowing, and ambiguity functions. Evaluation of probability of detection and false alarm rate for FFT and broadband signal processors. </p>    
                                </li>

                                <li>
                                    <p><em>Beamforming and Array Processing.</em> Beam patterns for sonar arrays, shading techniques for sidelobe control, beamformer implementation. Calculation of DI and array gain in directional noise fields. </p>
                                </li>

                                <li>
                                    <p><em>Passive Sonar Signal Processing.</em> Review of signal characteristics, ambient noise, and platform noise. Passive system configurations and implementations. Spectral analysis and integration. </p>
                                </li>

                                <li>
                                    <p><em>Active Sonar Signal Processing.</em> Waveform selection and ambiguity functions. Projector configurations. Reverberation and multipath effects. Receiver design. </p>
                                </li>

                                <li>
                                    <p><em>Passive and Active Designs and Implementations.</em>Advanced techniques for beamforming, detection, estimation, and classification will be explored. Optimal array processing. Data adaptive methods, super resolution spectral techniques, time-frequency representations and active/passive automated classification are among the advanced techniques that will be covered.</p>
                                </li>
                                <li>
                                    <p><em>Advanced Signal Processing Techniques.</em>Advanced techniques for beamforming, detection, estimation, and classification will be explored. Optimal array processing. Data adaptive methods, super resolution spectral techniques, time-frequency representations and active/passive automated classification are among the advanced techniques that will be covered. </p>
                                </li>



                            </ol>

                        </div>  


                    <button class="accordion">Tuition</button>
                        <div class="panel">
                            <p>The tuition for this three-day course is $1890 per person at one of our scheduled public courses. Onsite pricing is available. For more information or to register, please contact us at 410-956-8805 or send an email to <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e3f6ebc2e3f6ebe1edf7f0f1e7f1ace1edef">[email protected]</a>.</p>

                            <p><a href="https://www.aticourses.com/beta_mobile/register_secure.html">Register Now Without Obligation</a></p>
                        </div>
                </div>

Answer №1

If you wish for a specific accordion panel to be open by default when the page loads, you can update the script as follows:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  }
}

Modify it to look like this:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  }
}

// Additional code to automatically open the first section
if(acc.length > 0) {
  acc[0].classList.add("active");
  acc[0].nextElementSibling.style.maxHeight  = acc[0].nextElementSibling.scrollHeight + "px";
}

If you prefer not to have the first section open by default, you can specify a different index instead of 0.

Check out this codepen demonstration.

Answer №2

<script>
const accordionItems = document.getElementsByClassName("accordion");
let index;

for (index = 0; index < accordionItems.length; index++) {
  accordionItems[index].classList.toggle("active");
  const panelContent = accordionItems[index].nextElementSibling;
  panelContent.style.maxHeight = panelContent.scrollHeight + "px";
}
</script>

Answer №3

You have the ability to manually initiate a click event

<!DOCTYPE html>
<html>

<head>
  <style>
    button.accordion {
        background-color: #eee;
        color: #444;
        cursor: pointer;
        padding: 18px;
        width: 100%;
        border: none;
        text-align: left;
        outline: none;
        font-size: 15px;
        transition: 0.4s;
    }
    
    button.accordion.active, button.accordion:hover {
        background-color: #ddd;
    }
    
    div.panel {
        padding: 0 18px;
        background-color: white;
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.2s ease-out;
    }
  </style>
</head>

<body>

  <h2>Animated Accordion</h2>
  <p>Click on the buttons to open the collapsible content.</p>

  <button class="accordion">Section 1</button>
  <div class="panel">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
  </div>

  <button class="accordion">Section 2</button>
  <div class="panel">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
  </div>

  <button class="accordion">Section 3</button>
  <div class="panel">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
  </div>

  <script>
    var acc = document.getElementsByClassName("accordion");
    var i;
    
    for (i = 0; i < acc.length; i++) {
      acc[i].onclick = function() {
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight){
          panel.style.maxHeight = null;
        } else {
          panel.style.maxHeight = panel.scrollHeight + "px";
        } 
      }
    }
      
    /* open second panel by default */
    acc[1].click();
    
  </script>

</body>

</html>

Answer №4

To include the desired functionality, simply insert the following code snippet at the end of your script:

acc[1].click();

You have the flexibility to modify the index value within the code to suit your specific requirements for selecting and opening a particular section by default.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;

    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  }
}

acc[1].click();

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

Guide on how to print a particular DIV along with its corresponding CSS styling

Is there a way to print a specific DIV in JavaScript while including the styles within it? I have searched through several posts, but haven't found a solution that suits my needs. Is there a single function in JavaScript that can accomplish this? I h ...

"NaN is being caused by the presence of quotation marks within the split property

Apologies if this question has already been addressed, but I'm struggling to find the answer. I've recently delved into coding as a new hobby and found it quite enjoyable. After using a website that claimed I had learned all there is to know abou ...

Confirmation for deletion in HTML form

Is there a way I can include a confirmation message for deleting an item on my form button? Any suggestions on which JavaScript code to use? <script type="text/javascript"> function confirmDelete() { return confirm("Are you sure you want to delete ...

iPhone: Fixed position div disappearing

Currently, I am working on creating a mobile menu for my Joomla 3 site located at . The menu is functioning correctly on desktops, however, when attempting to view it on my iPhone, the menu slides in but remains invisible. Despite this, I can still tap on ...

An unexpected error occurs when attempting to invoke the arrow function of a child class within an abstract parent class in Typescript

Here is a snippet of code that I'm working on. In my child class, I need to use an arrow function called hello(). When I try calling the.greeting() in the parent class constructor, I encounter an error: index.ts:29 Uncaught TypeError: this.hello is ...

`CSS Content Placeholder Issue When Used Alongside JavaScript`

Let me explain a bit, I have a master page named UserProfile.master which has a content placeholder linked to UserProfileWall.aspx. Now, I am trying to incorporate some additional JavaScript and a second CSS file in the userprofilewall page. However, whene ...

Instructions for selecting all checkboxes in an HTML table with just one click

Developing an aspx page with 3 HTML tables, I am dynamically adding checkboxes to each cell. Additionally, I have a checkbox outside each table. When I check this checkbox, I want all checkboxes in the corresponding HTML table to be checked. However, curre ...

Manipulate numerous documents within MongoDB by updating them with varying data in each

I have a list of unique IDs: idList = ["5ec42446347f396fc3d86a3d", "5ec422d4347f396fc3d86a3c", "5ecefaf0aead3070fbdab7dd"] I want to update the documents that match these IDs with different data in each one: const currentData = await Data.updateMany( ...

Using jQuery to access a server-side SQL database through PHP

After searching for an example on connecting a client to a server's SQL database using JQuery, AJAX, and PHP, I came across this seemingly well-executed guide: Example Link. All my PHP files and the jQuery library (javascript-1.10.2.min.js) are contai ...

What is causing the text to not wrap around properly?

I'm currently facing an issue where the text that should not wrap around the image is wrapping, while the text that should be wrapped isn't. This is causing a layout problem in my coding section as shown here: https://i.sstatic.net/2oMn1.png The ...

What is the purpose of enclosing Arrow function body in parentheses?

While looking through a tutorial on survivejs, I came across a code snippet featuring a function with its body enclosed in parentheses: export default () => ( <ul> {notes.map(note => //some code )} </ul> ) The ...

Ensuring Data Accuracy Prior to Saving in Zend Framework 1.12

My form includes validations and a function to save data using ajax. Here is the structure of my form: <form name="enquiry_form" method="post" id="enquiry_form"> Full Name: <input name="name" id="name" type="text" pattern="[A-Za-z ]{1,20}" on ...

Creating a dynamic route in Node Express allows for flexible path handling

Is there a way to incorporate a dynamic route or path using the Express package? The challenge is that the path is an ID passed by the client and we have no control over it. const express = require('express'); const dynamicPath = express(); dyn ...

The state in Reactjs is not displaying as expected

Check out my ReactJS todo app that I created. However, I am facing an issue with deleting todos. Currently, it always deletes the last todo item instead of the one I click on. For example, when trying to remove 'Buy socks', it actually deletes ...

Engaging with ng-change and select: Modifying data source results in a change

Take a look at this plunkr: http://plnkr.co/edit/ke4Cjg3gnf2pWUKW1f2b?p=preview. var app = angular.module('app', []); app.controller('controller', ['$scope', '$timeout', function($scope, $timeout) { $scope.it ...

Eliminate specific elements from an array while retaining others

Here is a simple page setup: https://i.sstatic.net/z9MF9.png The page consists of an input field at the top, followed by a list (<ul>), and a button for saving changes. The <ul> is connected to an array called items. When the user clicks on "S ...

Achieving sequential actions in Javascript without the need for state updates

One aspect of jQuery that I find impressive is its ability to chain methods like .animate() and .css(). This is made possible by utilizing the special variable "this" in the backend code. I am interested in implementing a similar method chaining mechanism ...

What is the process for including a favicon on my website?

I am trying to add a favicon to my ASP website similar to this: https://i.sstatic.net/1dhXO.png After reading through these discussions: Image icon beside the site URL How to put an image on the tab bar next to the title of the page on the browser? I add ...

Issue with the useSWR hook causing the DOM not to update correctly due to mutation

My next.js app is utilizing the `useSWR` hook to fetch and populate data. const { data, error } = useSWR('/api/digest', fetcher, { revalidateOnFocus: false, }) The problem I am facing is that the DOM is not updating as expected after the `mu ...

Cannot retrieve Global variables when using chrome.tabs.executescript in Chrome 55

After recently updating Chrome to version 55.0.2883.75, I encountered an issue with my self-developed Chrome Plugin used for parsing HTML files. In the plugin, I utilize chrome.tabs.executescript to retrieve data from a background HTML page. Previously, I ...