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

The most effective method for monitoring updates to an array of objects in React

Imagine a scenario where an array of objects is stored in state like the example below: interface CheckItem { label: string; checked: boolean; disabled: boolean; } const [checkboxes, setCheckboxes] = useState<CheckItem[] | undefined>(undefined ...

What could be causing the npm mysql module to malfunction when trying to initiate the 'connect()' function in a separate .js file?

When I call require('mysql') and use the function connect() everything works fine. However, if I try to call the 'connect()' function in another file, it throws an error saying connection.connect is not a function... Any suggestions on ...

If the first dropdown menu has a sub-element, then the user should be able to select the same value in the second dropdown menu using jQuery

To trigger an alert, two HTML select option dropdowns must both have the value DIP EDU. My current code successfully accomplishes this, but there is a scenario where some options in the first dropdown may contain sub-elements. For example, selecting MBA wi ...

Custom filtering in jqGrid with an integrated filtering toolbar

Hey there! I'm currently using the latest version of jqGrid and I was curious if it's possible to implement local filtering with custom rules. In the past, I had to manually add this feature because the version I was using didn't support it. ...

Javascript involved in the process of CSS Background-Images loading after HTML Images

I quickly put together a microsite that is located at . If your internet connection isn't fast or nothing is cached, you may notice that the background-images used for CSS image-text replacement are the last items to load (especially the h1#head with ...

Child element failing to resize along with parent container

Here is the HTML structure I have for a template.php page within my website. <!DOCTYPE html> <html lang="en"> <head> <title></title> ...... </head> <body> <div id="container"> ...

The overflow property is not functioning as anticipated

I've browsed Google and this site, but I couldn't find a solution to my issue. On my webpage, I have a shoutbox and a teamspeak viewer with a specific height for the outer div. The scrollbars don't look good on our new design, so I attempt ...

Using an array.map inside a stateless component with React.createElement: the type provided is invalid

There is a component called BasicDetail in my code with the following structure: import React from "react"; import { Grid, Form } from "semantic-ui-react"; const BasicDetail = ({DetailData}) => { return( <div> <Grid.Ro ...

How can I ensure that the insertBefore function in jQuery only executes once, upon the initial click event?

jquery $(function(){ $('#4').click(function() { $('<input name="if4" type="text" value="other price>"').insertBefore('form textarea'); }); }); html <form> < input name="name" type="text" value="Enter yo ...

Creating a background overlay on top of an image background using styled-components in React: A step-by-step guide

I need help figuring out how to construct a unique component in react styled component that combines a background image with a black semi-transparent overlay. For visual reference, here is an example: https://i.sstatic.net/R6IBY.jpg ...

Troubleshooting the 'innerHTML' Issue in Your Python Selenium Script

My Python Selenium script for sending emails via Gmail is throwing an error, and I need some assistance to resolve it. The error details are as follows: Traceback (most recent call last): File "C:\Users\Administrator\Desktop\New ...

Multiplication and Division with Unit-ed Values in CSS calc() Function

Can you perform multiplication or division with unit-based values using calc() (such as 100%, 5px, etc)? For instance, I wanted to try something like this: width: calc(100% * (.7 - 120px / 100%)); Expecting it to result in something similar to (if 100% ...

Using various jQuery autocomplete features on a single webpage

UPDATE I have observed that the dropdown elements following the initial one are not being populated correctly. .data( 'ui-autocomplete' )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "i ...

Difficulty in adjusting the height of the popover menu that appears when using the Select Validator in Material UI

I am having trouble adjusting the height of a popover that emerges from a select validator form in Material UI. Despite attempting various methods, including adding the following CSS to the main class: '& .MuiPopover-paper': { height: &apos ...

What is the best way to show personalized messages to users using modal windows?

Encountering bugs while trying to implement user messages in modals. function displayMessage(title, description) { var myModalErrorMessage; $("#customErrorMessageTitle").text(title) $("#customErrorMessageDescription").html(description) myModalEr ...

Change the value of input on onClick event in React

Although this may seem simple, it is a little confusing to me. I'm having trouble understanding why the input value in the following case is not being reset. handleReset() { this.setState({ data: "" }); } <button onClick={this.handleReset}>R ...

Leveraging the csv file functionality in the npm package of d3 version 5

Currently in my react project, I am utilizing d3 for data visualization. After installing the d3 module via npm, I found myself with version 5.9.2 of d3. The challenge arose when attempting to use a csv file within d3. Despite scouring various resources, I ...

Execute and showcase code without redundancies

I have been exploring a way to store JavaScript code within an object and execute specific parts of it upon the user clicking a button. Here's what I've come up with so far: var exampleCode = { test: "$('body').css('background ...

TypeORM Error: Trying to access property 'findOne' of an undefined object

I've been working on implementing TypeORM with Typescript, and I have encountered an issue while trying to create a service that extends the TypeORM repository: export class UserService extends Repository<User> { // ... other service methods ...

Looking for assistance in correctly identifying types in react-leaflet for TypeScript?

Embarking on my 'first' project involving react-scripts-ts and react-leaflet. I am attempting to create a class that should be fairly straightforward: import {map, TileLayer, Popup, Marker } from 'react-leaflet'; class LeafletMap exte ...