Using div elements with a data attribute labeled as title in order to implement an accordion feature

Here is the structure I am working with to display titles before the corresponding div with data-attribute.

I am aiming to achieve this layout:

1st Title

2nd Title

3rd Title

4th Title

When "1st Title" is clicked, the layout should transform into:

1st Title

First Content

2nd Title

3rd Title

4th Title

My question is, is there a way to implement this accordion functionality without altering the existing HTML structure (which consists of ul, li elements followed by the content divs)?

ul {
  display:none;
  }

div:before {
  content:attr(data-title);
  display:block;
  font-size:14px;
  background:gray;
  text-align:center;
  line-height:14px
  }
  
div {
  background:lightgray;
  }
<ul>
    <li id="first">1st Header</li>
    <li id="second">2nd Header</li>
    <li id="third">3rd Header</li>
    <li id="fourth">4th header</li>
</ul>
<div id="first_div" data-title="1st Header title">First content <br/>1111111111111111111111</div>
<div id="second_div" data-title="2nd Header title">Second content <br/>22222222222222222222</div>
<div id="third_div" data-title="3rd Header title">Third content <br/>33333333333333333333</div>
<div id="fourth_div" data-title="4th Header title">Fourth content <br/>4444444444444444444</div>

Answer №1

Here is a solution that may be of assistance:

$('li').click(function(){
  if($(this).find('div.content').length == 0){
    $(this).append('<div class="content">' + $('#' + $(this).attr('id') + '_div').html() + '</div>');
    $('li').each(function(){
    if($(this).find('div.content').length != 0)
      $(this).find('div.content').slideUp();
    });
    $(this).find('div.content').slideDown();
  } else {
    if($(this).find('div.content').css('display') == 'block'){
      $(this).find('div.content').slideUp();
    } else {
      $(this).find('div.content').slideDown();
    }
  }
  
});
li {
 list-style: none;
}

div:before {
  content:attr(data-title);
  display:block;
  font-size:14px;
  background:gray;
  text-align:center;
  line-height:14px
  }
  
div {
  background:lightgray;
  }
  
.content{
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li id="first">1st Header</li>
  <li id="second">2nd Header</li>
  <li id="third">3rd Header</li>
  <li id="fourth">4th header</li>
</ul>
<div class="content" id="first_div" data-title="1st Header title">First content <br/>1111111111111111111111</div>
<div class="content" id="second_div" data-title="2nd Header title">Second content <br/>22222222222222222222</div>
<div class="content" id="third_div" data-title="3rd Header title">Third content <br/>33333333333333333333</div>
<div class="content" id="fourth_div" data-title="4th Header title">Fourth content <br/>4444444444444444444</div>

Hopefully, this solution proves useful for you.

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

Which is better to use: sql==true or sql===true?

Hey there, could you please take a look at this and thanks in advance! I'm currently working on developing a system for upgrading buildings in my game. I have set up a universal upgrade div that applies to all buildings. When the player clicks on a bu ...

What is the best way to create a placeholder for a select option with a looping value?

I have successfully implemented loops for the select options, but I needed to add a placeholder. In other words, I wanted the first value of the select options to be a placeholder, followed by the values generated from the loop. Here is the code that I u ...

Having trouble with submitting a form using @submit in Vue 3

I am facing an issue with the vuejs @submit.prevent feature in my login form. When I click the login button on my website, it does not work as expected. Even after adding a catch error in the function, the console still shows nothing. Can someone please as ...

Obtain a collection of chosen dates from the availability scheduler

I am currently working on an availability calendar where users can select multiple dates. While I have successfully been able to retrieve the value of each individual cell, I am facing difficulty in getting an array of values for all the cells selected. ...

What could be causing the partial failure of my CSS stylesheet in my Django application? Could it be related to retrieving data from the database?

After following various tutorials, including one on LinkedIn, I believe my Django settings are correct. However, I am facing an issue with the CSS stylesheet in my app. The styling works perfectly everywhere except for the section where I retrieve data fro ...

What about creating a PHP-MySQL voting platform?

I have implemented a PHP-MySQL voting system on my website, similar to YouTube's. I am using AJAX to execute the PHP in newtest.php. The PHP script works fine when tested individually, but when trying to implement the voting functionality through AJAX ...

Singling out a particular navigation tab

When attempting to link specific table IDs so that the corresponding tab is active when opened (i.e. www.gohome.com/html#profile), I am facing an issue where the active tab remains unchanged. Even after specifically calling out tab IDs, there seems to be n ...

The event onmouseover triggers actions on elements contained within

I am facing an issue with a div that acts as a container for text: <div class="timeSpanWrapper" data-occupied="false"> <span>@day.ToString("HH:mm", new System.Globalization.CultureInfo("da-DK"))</span> </div> Upon hovering ove ...

"Modify hyperlink attributes to enhance security and optimize user experience

$("a[href*='youtube']").attr('rel', 'prettyPhoto'); Having some trouble targeting links on a page containing "youtube" in the URL. I'm trying to set their rel attribute to "prettyPhoto" so they open in a lightbox window. ...

When $(.class) displays result, Javascript ceases execution

In the code snippet below, I am trying to load a group of products from a category when the user clicks on the .expandproducts button: $('.expandproducts').click(function(){ id = $(this).attr("data-id"); urlajax = document.location.origi ...

Struggling to receive accurate data from every statement

I have an object (known as allUserInfo) that looks like this: Object { available_client_ids: Array[2] 0: "demo" 1: "4532t78" available_client_names: Array[2] 0: "Demo" 1: "Bobs Bakery" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Altering webpage content through the use of Ajax

I need a solution for dynamically updating web page content using JavaScript AJAX. One idea I had was to store different div layouts in separate files, like so: BasicDiv.div: <div> <p>Some Text</p> <button> A Button </ ...

Verify if data is correct before refreshing user interface

When attempting to submit the HTML5 form, it stops the form submission if any required fields are missing a value or if there is another error such as type or length mismatch. The user interface then shows highlighted invalid fields and focuses on the firs ...

What is the best location to store the JWT bearer token?

Exploring options for storing JWT tokens in a Bearer header token for my application. Looking for the most efficient storage mechanism. Would love some insight on how to accomplish this using jQuery. Any recommendations for a secure method? ...

Prevent dragging of the div element that includes the "XYZ" class

I could really use some assistance as I am still learning j Query and Angular. I have a Div that serves as a container for another Div, and I am looking to prevent dragging on the Div with the class XYZ ...

The embed video is camouflaged within the bootstrap mobile display

I am currently using the latest version of bootstrap and bootswatch united theme to build and explore a standard website. The website is live at this link live site, featuring an embedded section on the right side as shown. My choice for the view engine is ...

What are the dimensions for maximum picture width and height in the Bootstrap 4 grid class col-4? Additionally, can you provide some tips on minimizing image bl

Hey there! I am trying to arrange 3 screenshots in 3 separate columns in one row, resembling steps 1, 2, and 3. I want them all to have the same size. Can you advise on the maximum width and height I should use before they start getting stretched or comp ...

What is the best way to transfer the string value parameter from a selected item in a dynamically populated dropdown list to a partial view controller in MVC 4?

I've set up an auto-populated dropdown list in my MVC 4 web application. The issue I'm facing is that when a user selects an item from the dropdown, I want only that specific item to be displayed in the partial view instead of all items. How can ...

Refreshing button labels in Rails utilizing ajax and jQuery

Despite researching numerous other SO inquiries, I am unable to make this function work as desired. Upon clicking "complete," I wish for the button to switch to "un-complete" (for example only). The AJAX action executes successfully, but I struggle with re ...

Maintain visibility of the vertical scroll bar while scrolling horizontally

Currently, I am in the process of setting up a table with fixed headers and columns that have a minimum width. To ensure this setup functions correctly, I require both vertical and horizontal scroll bars. The vertical scroll bar should only navigate throu ...