Guide for making an accordion with a close button that is specific to multiple dynamic IDs

I am looking to create an accordion feature. The idea is that when the user clicks on "Show," the text "Show" should be hidden, and the content along with a "Close" button should be displayed. Then, when the user clicks on "Close," the content and "Close" button should be hidden, and the "Show" button should be shown again.

It is important for all text to be in the HTML rather than in JavaScript. I also need this functionality to work with dynamic ID posts in Wordpress, so that more content can be shown and hidden on the index page.

I have made an attempt at implementing this, but unfortunately, the "Close" button does not seem to work as expected.

This feature needs to work with multiple ID items since it will be connected to the index posts page in WordPress.

Is it possible to change the class of the show/close buttons? Ideally, clicking on the parent element of the "Show" button would change the class of another element, and clicking on the parent element of the "Close" button would change the class of yet another element.

var $contents = $('.tab-content');
$contents.slice().hide();
$('.tab').click(function() {
  var $target = $('#' + this.id + 'show').show();
  $contents.not($target).hide();
});
.tab {
  background: red;
  max-width: 100px;
  cursor: pointer;
}

.close {
  border: 1px solid red;
  max-width: 100px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tab1" class="tab">Show 1</div>
<div id="tab1show" class="tab-content">
  content 1
  <div class="close">close</div>
</div>

<br><br><br>
<div id="tab2" class="tab">Show 2</div>
<div id="tab2show" class="tab-content">
  content 2
  <div class="close">close</div>
</div>

Answer №1

Check out this working fiddle.

Remember to include a click event for the close button as well, similar to this:

var $contents = $('.tab-content');
$contents.slice().hide();

$('.tab').click(function() {
  removeExtraClass();

  var $target = $('#' + this.id + 'show').show();
  var extraClass = 'post' + this.id.split('tab')[1] + 'long';

  $(this).hide().parent().addClass(extraClass);
  $('.tab').show();
  $contents.not($target).hide();
});

$('.close').click(function() {
  removeExtraClass();

  $(this).parent().hide();
  $(this).parent().prev('.tab').show();

  var $target = $(this).parent();
});

function removeExtraClass() {
  $contents.each(function() {
    var id = $(this).attr('id');
    var postClass = 'post' + id.split('tab')[1];

    $(this).parent().attr("class", postClass);
  });
}
.tab {
  background: blue;
  max-width: 100px;
  cursor: pointer;
}

.close {
  border: 1px solid blue;
  max-width: 100px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="postA">
  <div id="tabA" class="tab">View A</div>
  <div id="tabAshow" class="tab-content">
    content A
    <div class="close">close</div>
  </div>
</div>


<br><br><br>

<div class="postB">
  <div id="tabB" class="tab">View B</div>
  <div id="tabBshow" class="tab-content">
    content B
    <div class="close">close</div>
  </div>

  <br><br><br>
</div>

Answer №2

To implement the functionality, simply add an event listener on the element with the class .close.

var $contents = $('.tab-content');
$contents.slice().hide();

$('.tab').click(function() {
  var $target = $('#' + this.id + 'show').show();
  $(this).hide();
});

$('.close').click(function(){
  $(this).parent().hide();
  let parentId = $(this).parent().attr('id');
  parentId = parentId.replace('show','');
  
  $('#'+parentId).show();
  
});
.tab {background:red; max-width:100px; cursor: pointer;}
.close {border: 1px solid red; max-width:100px; cursor: pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  
  <div id="tab1" class="tab">Show 1</div>
  <div id="tab1show" class="tab-content">
  content 1
  <div class="close">close</div>
  </div>



<br><br><br>
<div id="tab2" class="tab">Show 2</div>
<div id="tab2show" class="tab-content">
  content 2
  <div class="close">close</div>
</div>

<br><br><br>

Answer №3

To close an event, simply use the following code:

$('.close').on('click',function(){
   $(this).closest('.tab-content').hide();
});

Here's a snippet of how it works,

var $contents = $('.tab-content');
$contents.slice().hide();
$('.tab').click(function() {
  var $target = $('#' + this.id + 'show').show();
  post = $target.closest('.post');
  post.addClass(post.attr('data-classes') + 'long');
  $allTargets = $contents.not($target);
  $allTargets.each(function() {
    post = $(this).closest('.post');
    post.removeClass(post.attr('data-classes') + 'long');
    $(this).hide();
  });
});
$('.close').on('click', function() {
  $(this).closest('.tab-content').hide();
});
.tab {
  background: red;
  max-width: 100px;
  cursor: pointer;
}

.close {
  border: 1px solid red;
  max-width: 100px;
  cursor: pointer;
}

[class$='long'] .tab {
  color: #FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="post1 post" data-classes='post1'>

  <div id="tab1" class="tab">Show 1</div>
  <div id="tab1show" class="tab-content">
    content 1
    <div class="close">close</div>
  </div>
</div>

<br><br><br>
<div class="post2 post" data-classes='post2'>
  <div id="tab2" class="tab">Show 2</div>
  <div id="tab2show" class="tab-content">
    content 2
    <div class="close">close</div>
  </div>
</div>
<br><br><br>

Answer №4

Here's a suggestion for you to try:

var $content = $('.tab-content');
$content.slice().hide();
$('.tab').click(function() {
  var $target = $('#' + this.id + 'show').show().addClass('long');
  $('.tab').show();
  $content.not($target).hide().removeClass('long');
  $(this).hide();
});

$('.close').click(function() {
  var tab = $('#' + $(this).attr('data-tab'));
  var tabContent = $(this).parent();

  tab.show();  
  tabContent.hide();
});
.tab {background:red; max-width:100px; cursor: pointer;}
.close {border: 1px solid red; max-width:100px; cursor: pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tab1" class="tab">Show 1</div>
<div id="tab1show" class="tab-content">
  content 1
  <div class="close" data-tab="tab1">close</div>
  </div>

<br><br><br>
<div id="tab2" class="tab">Show 2</div>
<div id="tab2show" class="tab-content">
  content 2
  <div class="close" data-tab="tab2">close</div>
</div>

<br><br><br>

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

Associate an alternate attribute that is not displayed in the HTML component

Imagine there is a collection of objects like - var options = [{ id: "1", name: "option1" }, { id: "2", name: "option2" } ]; The following code snippet is used to search through the list of options and assign the selected option to anot ...

Will there ever be a possibility in the future to compile from D 2.0 to Javascript?

An experienced C++ programmer (that's me) is venturing into other programming languages and considering the value of learning more about D 2.0. The clean, fresh rewrite of D has caught my eye with its pragmatic and wise choices. Now, I'm eager to ...

Choosing solely the following immediate sibling

After researching various solutions on different platforms for selecting the next sibling, I always encounter some kind of issue when implementing the suggested code. Here is the current structure I have: <div class="article" id="onea"> &l ...

Modifying the CSS design of specific columns within a table created using JavaScript

A unique way to showcase JSON data in a table is by utilizing a for loop within a function. This method, however, does not assign an ID or Class to the table. To hide the final three columns of this table using CSS, the following code can be employed (whe ...

Select an item by populating it with JQuery

Here is the select HTML code I am working with: <div class="form-group col-lg-6 row"> {{ Form::select( 'state',array( 0 => '' ),null, array( 'class' => 'form-control', 'data-placeholder' =&g ...

Implementing changes in the last loop iteration to impact the final result in Vue

Having recently delved into Vue, I'm having trouble figuring out how to solve this issue. Let me begin by showing you the code snippet followed by explaining the problem at hand. Currently, I am utilizing Vue-Good-Table for this project. methods:{ ...

Using JQuery to send an array to PHP and save it to a file

I am currently working on a project where I write test code that posts an array to a PHP page. The PHP page needs to write this array to a file in order to check the data. Here is the JQuery code snippet: $("#Trash").click(function () { $.post("tests ...

Addressing the issue with this.setState and this.state on the Registration page

I am facing an issue with my Registration Page code. I am trying to send data to a database using this.setState and this.state, but every time I run the code, it shows an error in the onSubmit function related to this.state. Can someone please help me unde ...

Unfulfilled promises are left hanging

I've encountered a problem while writing a unit test for my Angular application using Jasmine with a mock service. The promise I am trying to run is not functioning as expected. Below is the service code: CreateItemController = $controller('Cre ...

Enhancing the bottom border of an unordered list when incorporating styled bullets

I have a list with some items. I used a CSS trick to style the bullet as a circle. However, I would like to add a border underneath each item to separate them. Because I removed the default bullets using list-style: none, the "bullet" is positioned -1em, ...

Gradually fade with JavaScript

My JavaScript code below is used to recursively reload a specific DIV with the results of a data query. The issue I'm facing is that each time the DIV, identified by id="outPut", is reloaded, all the data fades in and out due to the fadeTo function. ...

Enhance Your Charts: Learn how to dynamically adjust zoom levels between two timestamps with just a simple form submission

I have a Zingchart Area Graph that displays events on a timeline with time on the X-Axis. I want to be able to automatically zoom into a specific timeframe on the graph based on user input from a form. For example, if a user selects a start time of 8 AM an ...

Executing jQuery post request on a div loaded via ajax

I'm facing a challenge with my webpage. I have a section where the content of a div is loaded via ajax. This div contains forms, and after submission, it should update to display the new content without refreshing the entire page. Can anyone guide me ...

When attempting to fetch JSON data using the Angular 2 `http.get()` method, the data returned is undefined and the component does not reflect any

My http-data.service is set up to accept json for output in the component template. Initially, the console displays that the first few calls return undefined, while subsequent calls start returning json. However, upon checking the component, it is evident ...

I am having trouble getting the pagination to function properly on my custom materialize projects

I am experiencing issues with the list of sub-pages on the official demo sites: Materialized Materialize(css) The navigation bar does not update the active page number or content when clicked. Both websites are using materialize css. If you click ...

Leveraging Parse methods within a Node JS Cron job

My current task involves writing a Cron Job that requires the use of Parse methods. I have the following code snippet at hand: var crontab = require('node-crontab'); var jobId = crontab.scheduleJob("* * * * * *", function(){ ...

Preventing Error in D3 Updates Caused by Invalid Path Formats

I'm encountering a problem with the d3 tree layout while dynamically adding nodes. When I add a path symbol to the node based on its type, I receive an error message "invalid path format" during updates. Both the Enter and update methods utilize the ...

jQuery append() is ineffective

I am having trouble with the append() function in all browsers. My goal is to have the "next" span display the text "Next hello" with a blue background when the page loads. (This code serves as a test to confirm that my jQuery is functioning properly. In ...

Block entry to HTML files unless the user has logged in utilizing PHP sessions

I have been working on implementing a verification process to check if a user is logged in when accessing a specific HTML file. When a user tries to access something.html without being logged in, I would like to redirect them to index.php and restrict acc ...

Setting the title of the master page body dynamically

Looking for a solution similar to the one discussed below, I am attempting to extract the title entered in the title tag on each page and use it to update an asp label dynamically to display the title on each page. My goal is to achieve this using only C# ...