Accordion panel overlapping when you select another one to open, causing the previously opened panel to close

I recently implemented an accordion feature on my website located at . You'll notice that there are two accordion fields named "DONE-FOR-YOU WEBSITE" and "WEEKEND WEBSITE WARRIOR". When you click on these fields, their respective panels open up as intended. However, I've encountered an issue where the panels overlap each other when opened simultaneously.

My goal is to ensure that only one panel is open at a time to prevent this overlapping behavior. Despite trying various solutions in my JavaScript code below, I haven't been successful in achieving this functionality.

        //Js file for accordian

var acc = document.getElementsByClassName("accordian-left");
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;
            panel.style.zIndex = "0";
            panel.style.border = "0";
            } else {
        panel.style.maxHeight = panel.scrollHeight + "px";
        jQuery(this).css('margin-bottom','10px');
        panel.style.zIndex = "1";
        panel.style.border = "3px solid #eee";
        } 
     }
  }

Answer №1

To enhance the functionality of your function, consider implementing a reset for each accordion panel before toggling the "active" class using a loop. Alternatively, you can streamline the process by iterating through all panels to hide them except for the clicked one:

function displayPanel(panel) {
    panel.style.maxHeight = panel.scrollHeight + "px";
    jQuery(this).css('margin-bottom','10px');
    panel.style.zIndex = "1";
    panel.style.border = "3px solid #eee";
}

function concealPanel(panel) {
    panel.style.maxHeight = null;
    panel.style.zIndex = "0";
    panel.style.border = "0";
}

function toggleDisplay(panel) {
    if (panel.style.maxHeight){
        concealPanel(panel);
    } else {
        displayPanel(panel);
    }
}

var acc = document.getElementsByClassName("accordian-left");
var i;
for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function() {
        var isHidden = false;
        for (j = 0; j < acc.length; j++) {
            if (this != acc[j] && acc[j].classList.contains("active")) {
                acc[j].classList.remove("active");
                concealPanel(acc[j].nextElementSibling);
                isHidden = true;
            }
        }
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (isHidden) {
            setTimeout(function() {
              toggleDisplay(panel);
            }, 400);
        } else {
            toggleDisplay(panel);
        }
    }
}

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

Nextjs couldn't locate the requested page

After creating a new Next.js application, I haven't made any changes to the code yet. However, when I try to run "npm run dev," it shows me the message "ready started server on [::]:3000, url: http://localhost:3000." But when I attempt to access it, I ...

Validation is only effective for the initial row and fails to apply to subsequent rows. This may be due to the necessity of including the return true/false statement in my validation process

HTML PHP <div align="center"><input type="text" class="form-control" id="<?php echo $i;?>" name="r2<?php echo $i+1;?>" onblur="mvalidate2()" style="text-align: center; bo ...

Automated pagination in Jquery running seamlessly

I have successfully created pagination using jQuery. Although the script is functioning properly, I now want it to automatically switch between different pages: <script> $(document).ready(function(){ $("#article_load_favourites").load("indexer_favo ...

Incorporating a background image into a card component using props

I attempted to add a background image to the card component through props, but the image failed to display on the card. I didn't encounter any errors, and I'm unsure what mistake I might be making. Any suggestions or alternative solutions would b ...

What methods does YepNope.js offer for assigning dynamic names to scripts?

Currently, I am utilizing YepNope.js to handle the loading of my css and javascript files. My query is regarding whether there is a method to assign variable names to these scripts during the initial process. For example: yepnope({ test : Modernizr.cs ...

Verifying Angular JS Routing: Ensuring the Current URL Matches the Route, including Dynamic URL Parameters

Just setting this up: app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/asd/:id/:slug',{ templateUrl:'views/home/index.html', controller:'Home', publicAccess:true, se ...

The error message "Nodejs TypeError: You can't use undefined as a function

While working through the Nodejs tutorial on Treehouse, I encountered an issue with the server response in the router. It seems that the view method in the renderer is not being found. router.js:10 response.view("header", {}, response); ^ TypeError ...

I am encountering an error that states: UnhandledPromiseRejectionWarning: TypeError: Unable to retrieve the property 'buffer' as it is undefined

I am facing an issue with my code where I am unable to upload new files to my website. Can someone help me understand what might be causing this problem? const multer = require("multer"); const upload = multer({ storage: multer.memoryStorage() ...

JavaScript reference problem when copying

Initially, I create a raw array by using the following initialization: $scope.rawUsers = angular.copy($scope.users); Subsequently, I make modifications to the data like so: function filterUsers(searchString, onlyMine) { $scope.users = []; _.find($scop ...

What is the importance of including the source name when redirecting?

In a recent discussion (jQuery Ajax PHP redirecting to another page), it was mentioned that when utilizing ajax for redirection to a PHP page, an event needs to be set in the following manner: $.ajax({ type: "POST", url: "ajax.php", data: dataString, ...

Ways to display distinct text boxes based on selected radio button?

Currently, I am working with JSP and have implemented an HTML form that includes a "Process" button at the top. When this button is clicked, it displays a form with two radio buttons - TestClient and TestServer. The form also contains a Submit button. If ...

The issue of Ajax failing to execute an HTTP POST request in an HTML environment

I am creating a sample HTML code that involves making HTTP post requests using an Ajax function. The task at hand is to execute 2 HTTP POST requests and 1 GET request sequentially based on the correct response received. POST: URL: http://localhost:8082 ...

Engage with a specific element within the Document Object Model even in the absence of a 'ref' attribute

Is there a better way to set focus on a button within a React component without using ref? The button is part of a third-party library and not immediately available upon componentDidMount. Currently, I am using setTimeout and querySelector which feels like ...

Exploring Javascript's Standard Object: A Guide to Retrieving Two Elements

If I have a special data object: var data = []; data["Name"] = ["Janet", "James", "Jean", "Joe", "John"]; data["Number"] = [25, 22, 37, 19, 40]; Let's say I'm looking for the minimum number value, which is '19' in this case. How ...

Trigger the restart of a jQuery function once the condition within it is satisfied

I have a payment page with various payment options displayed. If the selected payment option is 10, a list of banks that support that payment option is shown. When a bank is clicked from the dropdown list, I generate a button with the corresponding paymen ...

The margin 0 auto feature is ineffective, and instead, the target is activated upon the page's initial loading

As a beginner in CSS, I am encountering some issues with the HTML page of my application. I am currently working on an app and aiming to create a login view where the login form appears either after a voice command or button click. I am facing two main pro ...

Instead of displaying the location attribute in an alert, populate it into a text area

I have a function that can retrieve my current location using longitude and latitude coordinates. However, I am looking to automatically fill a text area (Populate Here) with the results instead of displaying an alert. <!DOCTYPE html> <html> ...

Using the .map method to index an array is causing issues in Node.js

Hey everyone, I'm struggling to properly index a JSON array using the map function. It seems like my code isn't quite right. This is what I have: var entireHTMLssssq = lloopmois.map((result, index) => `<div id=${index} style="position: a ...

What is the method for displaying html files in a POST request?

This is the code snippet I am working with: app.post('/convert', function(req,res){ var auxiliar = "somo Ubuntu command line(this works)"; exec(auxiliar, function(err, stdout, stderr){ if(err){ console.log ...

Troubleshooting PHP/MySQL integration with Google Maps - issues persist

I have come across several other posts on this theme but unfortunately, none of them have been able to help me. I am using the article https://developers.google.com/maps/articles/phpsqlajax_v3, however, the code provided is not working for me. I have a fil ...