JQuery: Ensuring only one panel is expanded at a time

Each time an <i> tag inside a <li> is clicked, it toggles the display of the following <ul>. To ensure that only one <ul> is expanded at a time, clicking on another <i> will collapse the previously expanded <ul>.

For a demonstration, check out my sample code

<ul class="nav-main">
    <li> <a href="/en/courses">Courses</a><i class="expand closed"></i>

        <ul class="drop">
            <li><a href="#">Campuses</a>
            </li>
            <li><a href="#">Online Learning</a>
            </li>
            <li><a href="#">Start dates and schedules</a>
            </li>
            <li><a href="#">Learning and Support</a>
            </li>
        </ul>
    </li>
    
    <li> <a href="#">Outcomes</a><i class="expand closed"></i>

        <ul class="drop">
            <li><a href="#">Career Starter Program</a>
            </li>
            <li><a href="#">Progress to a degree</a>
            </li>
            <li><a href="#">Career Pathways</a>
            </li>
        </ul>
    </li>
</ul>

Answer №1

To ensure that all panels are closed except for the one clicked, loop through each panel and close any that were not clicked on. You can view the updated fiddle here: https://jsfiddle.net/abc123/5/

Below is the relevant JavaScript code:

// Main Menu Slider
$('.nav-main .expand').on('click', function (e) {

    var clickedPanel = this;

    $('.nav-main .expand').each(function() {
        if (this !== clickedPanel && !$(this).hasClass('closed')) {
            $(this).addClass('closed').next('ul').slideUp(300, function () {
                $(this).removeAttr('style');
            });
        }
    });

    if ($(this).hasClass('closed')) {
        $(this).removeClass('closed').next('ul').slideDown(300);
    } else {
        $(this).addClass('closed').next('ul').slideUp(300, function () {
            $(this).removeAttr('style');
        });
    }
    e.preventDefault();
});

If I were you, I would consider extracting the open and close logic into separate functions to reduce duplication in the code.

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

spacing for margins of table elements generated dynamically

Despite setting the width for the td tag, there seems to be a significant gap between the Odo and Location columns. Below is a basic table structure: <table width="95%" border="0" cellspacing="0" cellpadding="2"> <tr> <td wi ...

Semi-transparent image

Can I achieve a semi-transparent image? Similar to this gradient: background:linear-gradient(to bottom,rgb(44, 44, 44),rgb(29, 38, 51,0.322)); ...

Obtaining the API for a website's functionalities

I’m in need of downloading the API file that facilitates the connection between the website and database. How can I achieve this? I've attempted to use Httrack, wget, and open explorer, but they only seem to download the website itself. While I get ...

Image Appears Oversized on Mobile Due to Responsiveness

Attempting to make this landing page responsive has been quite challenging. Unfortunately, on mobile devices the image extends beyond the width of the screen when in portrait mode, requiring users to scroll to view the images and form. My expertise lies in ...

Transfer dynamically generated table data to the following page

Seeking guidance on a common issue I'm facing. I am creating a table using data from Firebase upon page load, and I want users to click on a row to view specific details of that item. It may sound confusing, but it will make more sense with the code p ...

How can I retrieve the row index in an Angular Mat-Table that has expandable content?

Having a mat-table with expandable content on a page, I am seeking a solution to record the row number of the table when clicked. While I successfully achieved this with a regular table in the HTML file using: <tr mat-row *matRowDef="let row; columns: ...

Place small images onto a background image using drag and drop

I'm a beginner with jQuery and I'm looking to implement image dragging functionality on my website. Specifically, I have a base image where I want to be able to drag and drop smaller images onto it. Can anyone recommend any plugins or provide gui ...

Ignoring CSS transitions by changing the width property in JavaScript’s element.style

When attempting to create a smooth progress bar animation by adjusting the width using document.querySelector('#mydiv').style.width = '20%', I noticed that the new width is updated instantly rather than transitioning smoothly. It seems ...

"Centered in the middle of the screen, an animated

Encountering an issue with this code on Chrome. Clicking on the checkbox causes the text/checkbox to shift in position/padding/margin unexpectedly.. :( View the code on JSFiddle HTML <input id="inp" type="checkbox" /> <div id="cb" class="inp_ch ...

saving user information with asynchronous HTTP calls

I am encountering an issue while trying to save my form data using AJAX. When I submit the form data in a JavaScript file that calls another PHP file to perform an insertion operation, an error occurs. Here is the code snippet: <button id="submit" cl ...

Styling the footer to sit at the bottom of the page with a wider width, overlapping the content

I've encountered an issue where the footer of my webpage overlaps the content when the main content is long and users cannot scroll properly. Additionally, I've noticed that the width of the footer is larger than the header of the website. Below ...

Instructions for creating a JavaScript click function that iterates through all records, not just the initial record

Although I'm new to web development and still learning the basics of html, javascript, etc., I have a problem that seems quite simple. The challenge lies in understanding javascript functions, which I find particularly tough to grasp. Here's what ...

Utilizing jQuery's nextUntil() method to target elements that are not paragraphs

In order to style all paragraphs that directly follow an h2.first element in orange using the nextUntil() method, I need to find a way to target any other HTML tag except for p. <h2 class="first">Lorem ipsum</h2> <p>Lorem ipsum</p> ...

Streamline JSON Hierarchy

I am working with a script that generates JSON results in the following format: [ [ [ "maturity_date", "12/19/2017" ], [ "interest_rate", 0.22 ], [ "interest_earned", 264 ], [ "manage ...

Enhancing a video tag with a mysterious dark mask

I'm looking for a way to darken a video in my hero section to make it easier to see the white menu items that are getting lost in the brightness. Any tips on how to achieve this using CSS or Bootstrap? <template> <section class="se ...

Animate a DIV to the bottom of the page, then with another click, animate it back to the top

I've been working on a div animation where the original position of the div from the top is set at 70% and the div itself is set as absolute. However, when I click on a button, it slides to the bottom of the page with a top value of 95%. Now, my goal ...

Discovering the selected option's value in a dropdown and utilizing it to search through an array for data to fill another input

Is there a way to utilize the value of a select input option, created by a forEach loop, to extract the value of another property in the same array object and assign it as the value of a different input field? Apologies if this seems verbose or has been a ...

What is the best way to loop through several rows in jQuery by leveraging the power of AJAX, JSON, and PHP

In my PHP script, I have a function that fetches data from a database query and encodes it into JSON format. Here is an example of the code: while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) { $rows[] = $row; } print json_encode($r ...

`Modifying CSS in Bootstrap 4 for a personalized website design`

I am currently building a Bootstrap website for my sister, but I am facing issues with changing the CSS. Most of the time, the changes do not seem to take effect. I created a new file called "style.css" to override the Bootstrap styles and placed it below ...

What steps should I take to have a button initiate an AJAX request?

One of the tasks on my list involves a textbox and a button for interaction. Once text is entered into the textbox, I intend to trigger an AJAX request by clicking the button. The purpose of this AJAX call is to extract the text input and incorporate it i ...