Switch between multiple unordered lists (ul) so that when one list is clicked, the other lists reset to their initial state as though they were never

When I click on the first item in the ul list, it should slideToggle() to show its corresponding items. Similarly, when I click on the second item in the ul list, its items should slideToggle(), but the first ul list remains visible as well. What I am trying to achieve is that when I click on the first ul list, the items in the second ul list should automatically disappear and vice versa - clicking on the second ul list should hide the items in the first ul list. Here's the code snippet:

$("document").ready(function(){
$("#block1").click(function(){
$("#none1, #none2, #none3").slideToggle();
} );
$("#block2").click(function(){
$("#none4, #none5, #none6").slideToggle();
} );
});
#none1, #none2, #none3, #none4, #none5, #none6{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<ul id="first">
  <li id="block1"><a href="#">Block1</a></li>
  <li id="none1">None1</li>
  <li id="none2">None1</li>
  <li id="none3">None1</li>
</ul>

<ul id="second">
  <li id="block2"><a href="#">Block2</a></li>
  <li id="none4">None2</li>
  <li id="none5">None2</li>
  <li id="none6">None2</li>
</ul>

Answer №1

Here is a simplified solution that should meet your requirements by using siblings() and not() to target the other "block" elements

$(function(){
    var $blocks = $('#block1, #block2').click(function(){
        // slide up all siblings of other block(s)
        $blocks.not(this).siblings().slideUp();
        // toggle slide this one
        $(this).siblings().slideToggle();
    });
});

Check out the DEMO here.

Answer №2

The issue lies in your event handler code, which only specifies to display certain elements without hiding others.

To remedy this problem, you can make the following adjustments:

$("document").ready(function(){
    $("#block1").click(function(){
        $("#none1, #none2, #none3").slideToggle();
        if($('#none4').is(':visible')) { // block 2 lis are visible
          $("#none4, #none5, #none6").slideToggle();
        }
    });
    $("#block2").click(function(){
        $("#none4, #none5, #none6").slideToggle();
        if($('#none1').is(':visible')) { // block 1 lis are visible
          $("#none1, #none2, #none3").slideToggle();
        }
    });
});

Check out a live example on CodePen

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

Is the jquery autocomeplete plugin malfunctioning when using numbers in the input?

I encountered a requirement to display stock number suggestions within a search box. To achieve this, I decided to implement the Jquery autocomplete plugin. Through an ajax call to a function in my cfc, I was able to retrieve all the stock numbers and stor ...

Avoid reloading the page when submitting a form using @using Html.BeginForm in ASP.NET MVC

I have a webpage featuring a model that needs to be sent to the controller along with additional files that are not part of the model. I have been able to successfully submit everything, but since this is being done in a partial view, I would like to send ...

JQuery toggle button malfunctioning

Currently, I am in search of a simple replacement for the now deprecated toggle() method in jQuery. My goal is to create a smooth sliding effect for an element when a button is clicked, and have it slide back in the opposite direction upon clicking the sam ...

What is the best way to apply a texture to a triangle using three.js?

I've been able to add textures to cubes, spheres, and other primitives in a scene I created. However, when it comes to adding a texture to a simple triangle, I'm encountering difficulties. Below is my attempt at achieving this: var texture=TH ...

The PureComponent FlatList does not refresh properly even after including extraData={this.state} as a prop

After conducting some research, I discovered that using a PureComponent instead of a regular Component can enhance the performance of my FlatList. By doing so, only the row that was changed will be re-rendered rather than the entire list. However, I encoun ...

There seems to be an issue with AJAX file uploading functionality in Django

I'm facing an issue with uploading files using the onchange event and AJAX. I am only able to get the file path on the backend, not the actual file itself. My goal is to modify the code so that when a PDF file is selected, it automatically gets upload ...

Using a jQuery function within an Angular application requires a careful integration process to ensure

I developed a small program in Angular that includes a method for searching a string in an array of strings like this: function searchStringInArray(str, strArray) { for (var j = 0; j < strArray.length; j++) { if (strArray[j].match(str)) return j; ...

Ways to avoid unintentional removal of contenteditable unordered lists in Internet Explorer 10

How can I create a contenteditable ul element on a webpage while avoiding the issue in Internet Explorer 10 where selecting all and deleting removes the ul element from the page? Is there a way to prevent this or detect when it happens in order to insert ...

What could be causing the Twitter Timeline to fail to load based on a variable in a Vue.js component?

My goal is to display the Twitter timeline of multiple accounts based on the route. I initially attempted to use a plugin called vue-tweet-embed, but encountered issues with it. As a result, I resorted to the traditional method by embedding twitter's ...

The onClick functionality of a button may not work properly when nested within a DIV element in an ASP.NET project

Here is a snippet of code that includes a <div> element: <div id="specific"> <table cellpadding="2" border="0"> <tr><td>Choose category</td><td><select id="list_categories" runat="server"></select>< ...

interaction & portal

I am currently managing a website that includes an iframe. Both the main site and the embedded site within the iframe are verifying the $_SESSION["login"]. Therefore, if the session expires, the user will be automatically logged out. The issue I'm fa ...

Select objects from an array that are contained within another array of objects

I am dealing with an array of objects that contain various attributes such as weakness, id, and type. [ { weakness: [ "Fire", "Flying", "Ice", "Psychic" ], id: 1, type: [ "grass", "poison" ] }, ...

Guide to generating a dynamic manifest.json file for Progressive Web Apps using ReactJS

I am working on a project that requires me to generate a dynamic manifest.json file for my PWA (ReactJS). Below are the relevant code snippets: app.service.js: function fetchAppData() { const requestOptions = { method ...

Encountering an issue with eslint-loader in a new VueJS project: TypeError - eslint.CLIEngine is not recognized as

Embarking on a fresh VueJS venture with WebStorm. A brand new VueJS project has been established, NPM upgraded, Vuetify added, and upon server initiation, an error pops up: ERROR Failed to compile with 1 errors ...

Floating elements are misaligned and not laying out correctly

I've encountered an issue where the footer div is appearing behind the right-hand side div. I have a central container div with two floated divs next to each other, and the footer is separate. I've spent hours trying to fix it but can't figu ...

Increase the jQuery level and utilize the .find() method

Currently, I am delving into the realm of jquery and facing a minor hiccup with selectors. Below is the structure of my DOM: <li> <header class="title"> <span>Text</span> <a href="#work-1">My trigger</a> ...

Ways to restrict a function to a single DOM element using either its id or class

This script is responsible for dynamically loading pages on my website. It works fine, except that it currently iterates over all anchor tags a on the site, whereas I want it to iterate only through my navigation menu. Here is the navigation menu: <div ...

obtain the text content from HTML response in Node.js

In my current situation, I am facing a challenge in extracting the values from the given HTML text and storing them in separate variables. I have experimented with Cheerio library, but unfortunately, it did not yield the desired results. The provided HTML ...

Is it typical to experience a forced reflow violation and page offset?

After implementing a position: fixed on-scroll feature for my navbar, I noticed an error being thrown by the DOM stating: [Violation] Forced reflow while executing JavaScript took ms during every scroll event. It seems that this could be caused by layout t ...

What is the best way to locate an item reference for a specific DOM element?

Imagine a vast DOM structure with approximately 10,000 HTML elements, including 1,000 span tags. None of the span elements have any identifiers and are buried deep within other objects with long, complex Xpath paths that are not user-friendly for selectio ...