Accordion section appears on the webpage as it is loaded

I am currently working on implementing an accordion feature for my webpage. Everything is functioning correctly when I click the button, but there is one issue - the div opens automatically when the page loads. My goal is to have the div closed initially and only open when the button is clicked.

<a href="" class="accordion">Click here</a>
 <div class="panel" id="AccordionDiv">
            <div class="store">
                <div class="store-row">

                    <div class="cells store-logo text-center">
                        <img src="@strStaticWebsiteUrl@(objOfferPrice.StoreImage)" alt="" />
                    </div>

                    @if (objOfferPrice.Price < objOfferPrice.UrlPrice)
                    {
                        <div class="cells text-center">
                            <div class="product-price offer-price">Rs. @String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:0,0}", objOfferPrice.Price)<sup>*</sup></div>
                            <p class="real-price">Price: @objOfferPrice.UrlPrice</p>
                        </div>
                    }
                </div>
           </div>

The following code snippet includes HTML and JavaScript:

            <script>
                var acc = document.getElementsByClassName("accordion");
                var i;
                for (i = 0; i < acc.length; i++) {
                    acc[i].addEventListener("click", function () {

                        this.classList.toggle("active");
                        var panel = this.nextElementSibling;
                        if (panel.style.display === "block") {
                            panel.style.display = "none";
                        } else {
                            panel.style.display = "block";
                        }
                    });
                        }
            </script>

Answer №1

To hide the panel div, simply include style="display:none"

Modify

 <div class="panel" id="AccordionDiv">

Into

 <div class="panel" id="AccordionDiv" style="display:none">

View working demo

Answer №2

To ensure the accordion is closed by default, include an inline style of "display:none" in your code. It is advisable to use separate classes for open and close states and toggle between them instead of including inline styles.

Answer №3

Initially hidden, this content will appear when a button is clicked

<div class="panel" id="AccordionDiv" style="display:none";>


     <script>
      window.onload = function(){
            var acc = document.getElementByClassName("accordion");
            var i;
            for (i = 0; i < acc.length; i++) {
                acc[i].addEventListener("click", function () {

             document.getElementById("AccordionDiv").style.display="block";
                    this.classList.toggle("active");
                    var panel = this.nextElementSibling;
                    if (panel.style.display === "block") {
                        panel.style.display = "none";
                    } else {
                        panel.style.display = "block";
                    }
                });
                    }}
        </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

Why won't JavaScript functions within the same file recognize each other?

So I have multiple functions defined in scriptA.js: exports.performAction = async (a, b, c) => { return Promise.all(a.map(item => performAnotherAction(item, b, c) ) ) } exports.performAnotherAction = async (item, b, c) => { console.log(`$ ...

Retrieve 10000 sets of coordinates in real time with the help of Google Maps

I am trying to retrieve coordinates for 10,000 lines of data using the Google Maps geocoding API and display each line on the browser. My strategy involves looping through each line (which contains an address), passing it to the Google Maps URL, parsi ...

Distinguishing between client side rendering and server side rendering is the backbone of web development

My goal is to give users the option to request webpages from my website either directly from the server or by clicking on links, which will be managed by Backbone's router. When a user requests a webpage directly from the server, they will receive a ...

various demands utilizing ajax

I am faced with a challenge where I have a form that can potentially have anywhere from 1 to 5000 fields. When these fields are sent via AJAX, I need them to be sent in batches of 10 due to the limitations of serializing requests. How can this be achieved? ...

Manipulating an element in the JSON data is causing alterations to the preceding elements

I am facing a challenge with two JSON arrays. $scope.arr1 = [ { "id": 1, "first_name": "Philip", "last_name": "Kim", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e6e7577732e5e737b7a777f78776c7b307d717 ...

Exploring the capabilities of an Angular factory

I am facing challenges in improving the unit test coverage of an Angular project, particularly when trying to test an AngularJS factory with multiple dependencies. The factory I am working on has 5 dependencies, and I am struggling to even write a basic t ...

What is the reason for the retrieval of jquery-3.5.1.min.js through the request.params.id expression?

For my school project, I am using Express.js with TypeScript to create a simple app. This router is used for the edit page of a contact list we are developing. It displays the ID of the current contact being edited in the search bar. The problem arises whe ...

The text is exceeding the boundaries of its container, displaying in a single line that extends beyond the page

I am currently working on incorporating text into the project-details section by utilizing a rich text uploading field in Django admin. Despite inputting the text as a paragraph in the Django admin project description, it displays as a single line that ove ...

Connect parent-child models with checkboxes

Currently, I am working on an application where I need to link checkboxes for a role-based menu. The challenge lies in dealing with parent-child checkboxes and ensuring that the values of checkboxes are checked based on user input 1, 1.1, 1.2, 2, 3. Despi ...

Unable to adjust the width of the react-select component

I've been struggling to adjust the width of the select element but no matter what I try, it remains at a default width of about 75px. const CustomContainer = styled('div')` width: 100%; height: 100%; display: flex; flex-flow: row wr ...

What could be causing the issue with my validation for alphabetical input?

I am currently working on a registration form that only accepts alphabetical input. However, I am facing an issue where my error message appears regardless of whether I input an alphabetical or special character. According to my understanding, the code sho ...

Using JQuery Datatable plugin to bind data in ASP.NET MVC applications

Having trouble implementing the JQuery Datatable plugin in my ASP.NET MVC application. Despite receiving JSON data from the controller, the table is stuck displaying a "Loading..." message. Here is my controller code: public ActionResult GetCompanies(jQu ...

How to format numbers with commas in AngularJS to make them easier to read

One of my variables looks like this: $scope.numbers = 1234567. When I apply the filter {{numbers| number : 0}}, the result is 1,234,567. Is it possible to get a result like 12,34,567 instead? Thank you in advance. ...

Optimal method for parsing URLs using ES6

There have been many remarkable inquiries regarding this topic, such as: how to parse a url. However, as time has gone by, the answers I come across are outdated. I am looking for a more modern and flexible method to parse URLs, without relying on regular ...

How to Use JQuery to Retrieve the Nearest TD Element's Text Content

Hey there, here is some HTML code that I need help with: <tbody> <tr> <td class="text-center"><input type="text" class="form-control cardSerialNumber"></td> <td class="text-center"><button type="button" onc ...

React Alert Remove Alert: Each item in a list must be assigned a distinct "identifier" prop

How can I resolve the React warning about needing a unique "key" prop for each child in a list? I'm trying to eliminate the warning that says: "Each child in a list should have a unique key prop." The code snippet causing this warning is shown below ...

Tips for saving and accessing Shopping Cart items using localstorage

As I develop a shopping cart for an e-commerce site, I aim to utilize browser localstorage to store the products. The functions that have been added to my code include: - addToCart(): triggered when the "Add to Cart" button is clicked. - addProduct(): ...

Modify the color of the text input by the user in an AJAX-enhanced text box

After successfully implementing an autocomplete textbox using AJAX Autocomplete, I decided to enhance the feature with some Fuzzy logic. Now, as the user enters 3 characters, my database returns a list of records that match those characters. The search re ...

The NextAuth file imported with the EmailProvider is currently not being utilized

Having an issue with implementing nextauth for authentication. I have imported EmailProvider from nextauth/providers but when I try to use it in the Nextauth providers object, it does not recognize the EmailProvider that I've imported. Here is the co ...

Ways to configure an Express.js server file with the router path set as the root directory

I have a directory structure set up like this root private js css index.html app.js privateRouter.js ... Within my index.html, I am referencing the js and css files using relative paths: <link rel="stylesheet" href="css/index.css" ...