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

Unexpected compatibility issue with Chrome! Same AJAX feature flawlessly executed in Firefox but troubleshooting points to a potential event-related

I'm facing an issue where my script is functioning perfectly on Firefox but not working on Chrome. The script code I am using is as follows, where "r_tour" is the id of the select element and "option" is one of the options: $("#r_tour option").click ...

What is the best method to modify the hover text color in a Bootstrap navbar?

Whenever the cursor hovers over the letters, I attempted to modify their color, but unfortunately, it didn't work as expected. nav a { text-decoration: none; } .logo { height: 3rem; } .navbar-nav .nav-item .nav-link.custom:hover { color: ...

Trouble with triggering events from Datatable buttons

Below is the code snippet I am currently using for my DataTable : var oTable12= $('#example').DataTable({ "aaData": tableData, "aLengthMenu": [[5, 10, 20, -1], [5, 10, 20, "All"]], "iDisplayLength": 5, "aoColumnDefs ...

Retrieving a value from an array at random to assign to a different variable

I have different options for a specific variable depending on the scenario --> var lowSpeed = Math.random() * (45 - 30) + 30; var mediumSpeed = Math.random() * (60 - 45) + 45; var highSpeed = Math.random() * (80 - 60) + 45; var highwaySpeed = Math.rando ...

Shadow effect is present under every cell in the table row

I am struggling to create an HTML table with proper vertical spacing between rows and a shadow effect beneath each row. Unfortunately, the shadow always ends up overlapping other table content. I have tried adjusting the positioning of elements and setti ...

What is the best way to alter the background of a div when hovering over an image?

I am looking to achieve a unique effect with my thumbnail image and background. Currently, I have the thumbnail image inside a div with another image serving as the background to frame it. My goal is to change the position of the background image from bott ...

Exploring the possibility of integrating direct search functionality into the URL bar within an Angular application

One interesting feature I observed on GitHub is that after typing "github.com" in the URL bar, you can directly search by pressing the spacebar, which activates the "search mode." Here's how it looks like on Chrome: I'm curious, how can I implem ...

aligning JSON information with JavaScript object

I am currently in the process of setting up a sample dataset in JSON format for a JavaScript tutorial that I'm going through. Here's how the data object looks in JavaScript: app.Book = Backbone.Model.extend({ defaults: { coverImage: ...

Eliminating an element from an array depending on the value of its properties

I need to remove an object from my List array by matching its properties value with the event target ID. Currently, I am using findIndex method to locate the index ID that matches the event.target.id. Below is an example of one of the objects in my list a ...

Deactivate a <tr> element if any of its <td> cells contain a value

In my table, there are various trs and tds with different element names. I need to determine if there is text in a specific field. If there is text, I want to disable or hide the entire tr to prevent user interaction. Unfortunately, I am unable to provide ...

Angular2 - receiving an error message stating that this.router.navigate does not exist as a

Currently, I am delving into the world of Angular2 with Ionic and working on crafting a login page. However, upon loading the page, an error surfaces: 'router.initialNavigation is not a function' To address this issue, I inserted '{initialN ...

HTML5 canvas game issue: background fails to load

I'm a beginner at designing games using HTML5 canvas. I've been following a tutorial on creating games in the style of Angry Birds from the 'pro html5 games' book. I've completed all the steps in the tutorial, but I'm facing a ...

Having difficulty retrieving objects within a foreach loop of object keys that do not meet the criteria of the string.prototype.replace method

Currently, I am working on looping over objects within a key:value array in JavaScript to use the string.prototype.replace method for paths to JS files in GulpJS concat tasks. The objective is to generate a list of paths that GULP can utilize, but they re ...

Avoid executing top-level path middleware with app.use('/') in Express routing when directly accessing child or nested paths

Perhaps the title may not be as accurate as I hoped, but I have a very simple example to share. On my website, there are two main areas - a public area and a restricted admin area. example.com/admin (admin home page) example.com/admin/news (news page) ...

CSS, Assistance in incorporating a sub menu into a drop-down menu

I'm looking to enhance my drop down menu by adding a sub menu. Specifically, I would like to create a sub menu for Item 3 in the HTML below. How can I achieve this? Thank you, Below is my CSS code: .nav_menu { width:100%; background-color:# ...

Troubleshooting Problems with Owl Carousel Loading

Having trouble with Owl Carousel loading issue. I've set up my carousel using the Owl Carousel jQuery plugin as guided, but it's showing me an "owl-carousel loading" class added to the DOM (owl-loading). I've tried adding custom styles and J ...

Placing a div tag directly beneath another div tag

Imagine you have a div element with the class name divstudent, let's call this one div1. Now, you want to dynamically create another div element below div1, but outside of it using JavaScript. How can you achieve this? "div1" <div class="divstuden ...

The perfect method for creating template literals using a function

I have a function that accepts an argument called id and returns a template literal: const generateTemplate = (id) => { return `<div style="box-sizing: border-box; height: 32px; border-bottom: 1px solid #ECECEC; color: #282828; padding: 8px; dis ...

The $route object in Vue is not configured

Currently, I am delving into the realm of Vue router and aiming to achieve programmatic navigation without relying on <router-link> in my templates file. Here is a glimpse of my router and view setup: router = new VueRouter({ routes: [ ...

Is there a way to deactivate the Edge mini menu while selecting text in a React application?

I have recently been working on a React web application and managed to create a specialized text selection menu. However, I am facing a challenge in programmatically disabling the default text selection mini menu in React. The image attached illustrates bo ...