Creating a collapsible accordion feature with jQuery using a specific HTML layout: wanna learn how?

I am looking to create an accordion effect with the structure provided below. The goal is to have the corresponding article toggle when clicking on .booklist>li>a, allowing only one article to be open at a time. Can someone assist me with writing this script? Jquery implementation is encouraged.

http://jsfiddle.net/vinicius5581/r2zevb3d/1/

CSS

article{
     display:none;
 }

HTML

<section>
<ul class="booklist">
     <li>
         <a>Article Name 1</a>
         <article>                        
              <p><content</p>
              <img class="left" src="myimage"/>
              <p>more content</p>
          </article>
     </li>
     <li>
         <a>Article Name 2</a>
         <article>                        
              <p><content</p>
              <img class="left" src="myimage"/>
              <p>more content</p>
          </article>
     </li>
     <li>
         <a>Article Name 3</a>
         <article>                        
              <p><content</p>
              <img class="left" src="myimage"/>
              <p>more content</p>
          </article>
     </li>

Answer №1

Check out this code snippet for toggling articles on click:

$(document).ready(function(){
    $('.booklist>li>a').click(function(){
        $(this).next('article').slideToggle();
        $(this).closest('li').siblings('li').find('article').slideUp();
    });
});

View Updated Demo

Answer №2

It seems like I found the solution you were seeking:

$(".booklist li").click(function(){
  $(this).find("article").slideToggle().end().siblings("li").find("article").slideUp();   
});

Check out the JSFIDDLE link for a live demo!

Answer №3

All you need to do is implement the code snippet below

$("button").on('click', function(){
    $(this).siblings("section").slideToggle()
       .closest("div").siblings("div").find("section").slideUp();
});

DEMO

Answer №4

HTML

<section>
    <ul class="booklist">
        <li> <a href="#">Article Name 1</a>

            <article>
                <p>
                    <content</p>
                        <img class="left" src="myimage" />
                        <p>more content</p>
            </article>
        </li>
        <li> <a href="#">Article Name 2</a>

            <article>
                <p>
                    <content</p>
                        <img class="left" src="myimage" />
                        <p>more content</p>
            </article>
        </li>
        <li> <a href="#">Article Name 3</a>

            <article>
                <p>
                    <content</p>
                        <img class="left" src="myimage" />
                        <p>more content</p>
            </article>
        </li>
    </ul>
</section>

CSS

ul, li, h4, p {
    margin:0;
}
li {
    list-style:none;
}
.booklist li a {
    cursor: pointer;
}
.booklist li article {
    display: none;
}

Script

$(document).ready(function ($) {
    $('.booklist').find('a').click(function () {

        //Expand or collapse this panel
        $(this).next().slideToggle('slow');

        //Hide the other panels
        $(".booklist li article").not($(this).next()).slideUp('slow');

    });
});

Fiddle Demo

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

Discovering the identical element within the ajax response

The following section is being targeted: var obj = $(this).parent().find('a'); // $(this) is a <UL> inside a <DIV>, but there can be multiple DIV>ULs on the page After that, I retrieve some HTML using $.ajax(). This HTML corres ...

What is the process for retrieving data from mongoDB and displaying it by year in a single row?

I have received an array of data from MongoDB, which includes id, userName, and date. The date consists of years and months. My goal is to display this data categorized by years. How can I construct a query to the database that will show the data for all y ...

Encountering a mysterious error while attempting to access and modify a value stored in a useState hook using the keydown

I've been attempting to create a simple animation on canvas using React.js, but I'm facing an issue with integrating my Keydown function with my useState. It seems that my useState value is not being defined properly, preventing me from changing ...

What could be the reason for receiving an undefined user ID when trying to pass it through my URL?

Currently, I am in the process of constructing a profile page and aiming to display authenticated user data on it. The API call functions correctly with the user's ID, and manually entering the ID into the URL on the front end also works. However, wh ...

Is it possible to click the back button on your browser and return to an ajax page while keeping it in the same appearance?

I've been researching different jquery history plugins, but I haven't come across any examples that fit my specific situation. This is leading me to believe that what I'm trying to accomplish may not be feasible. Our search page is highly c ...

Issue with updating input value during keyup event in Android Chrome specifically

Check out this straightforward jsfiddle: https://jsfiddle.net/gq9jga4q/33/ <input type="text" id="kbdhook" /> <div id="result" >1: </div> <div id="result2" >2: </div> <div id="result3" >3: </div> $('#kbdh ...

Table gets duplicated data with JQuery JSON updates

After thorough searching, I couldn't find any relevant information on stack overflow that matches the issue I am encountering. The problem arises with a JQuery ajax request that retrieves JSON data from my server. The structure of the data is as foll ...

Guide to creating a delayed response that does not block in Node and Express

I want to implement a delayed response to the browser after 500ms has elapsed. app.post('/api/login', function(req, res) { setTimeout(function() { res.json({message: "Delayed for half a second"}); }, 500); }); The code snippet a ...

Exploring the process of dynamically inserting choices into an array of HTML dropdown menus using a combination of Php, AJAX, and jQuery

My task involves populating an HTML array of 10 select fields with jQuery every time a div-popup is called. The purpose of this form is to facilitate the batch approval of staffing requests for hundreds of employees by upper management, organized by depart ...

Determining age in a Class upon instance creation

Is there a way to encapsulate the age calculation function within the Member Class without resorting to global space? I want to automatically calculate and set an age when creating an instance. Currently, I have a function that works, but I'm curious ...

Is it possible for me to hand over control to a child process and retrieve the result in Node.js?

Recently, I encountered an issue where multiple simultaneous GET requests to my Node.js server caused it to become overwhelmed and unresponsive, leading to timeouts for clients (503, service unavailable). Upon thorough performance analysis, I discovered t ...

Want to learn how to create a draggable uploaded image on a canvas, similar to the functionality of Google

I have a question regarding the draggable feature in Canvas elements. I uploaded an image into the canvas and would like it to be draggable, similar to Google Maps. My ultimate goal is to enable zoom in and out functionalities as well. Is this achievable ...

Tips for arranging various information into a unified column within an Antd Table

Is there a way to display multiple data elements in a single cell of an Ant Design table, as it currently only allows insertion of one data element? I am attempting to combine both the 'transactionType' and 'sourceNo' into a single cell ...

Mastering Protractor's end-to-end control flow and managing time outs

When testing an angular app using protractor, I encountered a strange issue recently. Every now and then, or since a recent update, protractor seems to stall or slow down significantly. After investigating the problem, I discovered that a simple someEleme ...

What is causing the element to disappear in this basic Angular Material Sidenav component when using css border-radius? Check out the demo to see the issue in action

I have a question regarding the Angular Material Sidenav component. I noticed that in the code below, when I increase the border-radius property to a certain value, the element seems to disappear. <mat-drawer-container class="example-container" ...

Get rid of the blue dots that appear on anchor tags

I am facing a strange issue with the anchors on my webpage. There are a few anchor tags in my body: <a href="link1.html"></a> <a href="link2.html"></a> <a href="link3.html"><img src="img1.png" /></a> Interestingl ...

Modifying the 'child' node within a JSON object

Exploring the implementation of d3s Collapsible tree using a custom node hierarchy. My dataset structure deviates from the norm, for example: http://jsfiddle.net/Nszmg/2/ var flare = { "Name": "Example", "members": [ { "BName":"Ja", ...

Extract the links from the database using AngularJS

Currently, I am utilizing Laravel 5 for the backend and Angular.js for the frontend. The application operates solely through ajax requests. In my view, I have static links that are always visible on any page. Here is an example of how they are displayed: ...

Encountering the error `RollupError: Expression expected` during the compilation of an NPM package

Following the setup of my environment to create my initial NPM package for React JS with ROLLUP bundler, I encountered a RollupError: Expression expected error message as displayed below: Error Message > rollup -c --environment NODE_ENV:development dev ...

Why is ng-change not functioning properly, especially in conjunction with the Select element?

HTML <select ng-model="selectedName" ng-change="retrieveSelectedClass()" ng-options="(item.name||item) group by item.groupName for item in names" class="code-helper" id="code-helperId"> <option value="">Select Option</op ...