Close CSS Accordion when Clicked

I have a CSS accordion that I would like to close each panel upon clicking. Can this be accomplished using only CSS, or will JavaScript need to be added?

#accordion input:not(:checked) + div {
  display: none;
}

#accordion input:checked + div {
  display: block;
}

#accordion input {
  width: 0px;
  height: 0px;
  margin: 0px;
  opacity: 0.0;
}

#accordion label {
  cursor: pointer;
  display: inline-block;
  width: 750px;
  background: #ffffff;
  color: #ff6600;
  font-family: open sans;
  border: 1px solid #ff6600;
  font-size: 24px;
  padding: 25px 20px;
  margin: 0px;
}

#accordion div {
  width: 750px;
  background: white;
  border: 1px solid gray;
  padding: 15px 20px;
}

#accordion li {
  list-style: none;
}
div.scroll {
  max-height: 1050px;
  overflow: auto;
}
.timely-stream:not(.timely-agenda) .timely-event {
  min-height:92px; !important
}
<ul id="accordion">
<li>
<label for="section-1-checkbox">OneHockey</label>
<input id="section-1-checkbox" type="radio" name="accordion-level-1" />
<div><a href="https://imgur.com/HJwXuym"><img 
src="https://i.imgur.com/HJwXuym.png?1" width="750px" height="422px" 
title="source: imgur.com" /></a></div>
</li>
<li>
<label for="section-2-checkbox">TOURNAMENTS</label>
<input id="section-2-checkbox" type="radio" name="accordion-level-1" />
<div class="scroll">
<script src="//dashboard.time.ly/js/embed.js" data- 
src="https://events.time.ly/hye2ww2?categories=21029&organizers=43496" 
data-max-height="0" id="timely_script" class="timely-script"></script>
</div>
</li>
<li>
<label for="section-3-checkbox">INFO</label>
<input id="section-3-checkbox" type="radio" name="accordion-level-1" />
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
</li>
<li>
<label for="section-4-checkbox">STANDINGS/SCHEDULE</label>
<input id="section-4-checkbox" type="radio" name="accordion-level-1" />
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
</li>
</ul>

Answer №1

In reference to my previous comment: If the requirement is to enable the deselection of an item by clicking on it, switching from radio buttons to checkboxes is necessary. However, this switch allows for multiple panels to remain open. To achieve the functionality of automatically closing other panels when a new one is opened and closing the open panel upon clicking it again, some amount of JavaScript is required.

Below is your code with two minor adjustments:

  1. Changed from radio buttons to checkboxes.
  2. Added a small jQuery snippet that implements the "accordion" behavior of closing other panels when one is opened.

jQuery(function($) {
  $('input[type="checkbox"]').on('change', function() {
    let state = $(this).is(':checked');
    $('input[type="checkbox"]').prop('checked', false);
    $(this).prop('checked', state);
  });
});
#accordion input:not(:checked)+div {
  display: none;
}

#accordion input:checked+div {
  display: block;
}

#accordion input {
  width: 0px;
  height: 0px;
  margin: 0px;
  opacity: 0.0;
}

#accordion label {
  cursor: pointer;
  display: inline-block;
  width: 750px;
  background: #ffffff;
  color: #ff6600;
  font-family: open sans;
  border: 1px solid #ff6600;
  font-size: 24px;
  padding: 25px 20px;
  margin: 0px;
}

#accordion div {
  width: 750px;
  background: white;
  border: 1px solid gray;
  padding: 15px 20px;
}

#accordion li {
  list-style: none;
}

div.scroll {
  max-height: 1050px;
  overflow: auto;
}

.timely-stream:not(.timely-agenda) .timely-event {
  min-height: 92px;
  !important
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="accordion">
  <li>
    <label for="section-1-checkbox">OneHockey</label>
    <input id="section-1-checkbox" type="checkbox" name="accordion-level-1" />
    <div>
      <a href="https://imgur.com/HJwXuym"><img src="https://i.imgur.com/HJwXuym.png?1" width="750px" height="422px" title="source: imgur.com" /></a>
    </div>
  </li>
  <li>
    <label for="section-2-checkbox">TOURNAMENTS</label>
    <input id="section-2-checkbox" type="checkbox" name="accordion-level-1" />
    <div class="scroll">
    </div>
  </li>
  <li>
    <label for="section-3-checkbox">INFO</label>
    <input id="section-3-checkbox" type="checkbox" name="accordion-level-1" />
    <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
  </li>
  <li>
    <label for="section-4-checkbox">STANDINGS/SCHEDULE</label>
    <input id="section-4-checkbox" type="checkbox" name="accordion-level-1" />
    <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
  </li>
</ul>

Answer №2

To achieve this functionality, you'll need to utilize JavaScript. Begin by creating a button with the ID 'close'.

jQuery(function($) {
   $( "#close" ).click(function() {
       $( "#target" ).toggle();
    });
});

With the above code, the element will be hidden using JavaScript. Alternatively, you can use the following code snippet:

jQuery(function($) {
    $( "#close" ).click(function() {
         $( "#target" ).addClass('hidden');
     });
});

Here, 'hidden' is defined as:

hidden: display: none;

Answer №3

This method may not look visually appealing, but it achieves the desired functionality without the need for JavaScript.

By utilizing standard links and the :target pseudo class, you can achieve the desired accordion effect.

To implement this, link to the li element containing the target accordion item. Then, display the item while toggling the open and close links accordingly.

Although this method works, personally, I would opt for a more straightforward JavaScript solution.

/*Hide child div*/
#accordion li > div {
  display: none;
}
 
 #accordion li a.close {
  display: none;
}

/*Display target div*/
#accordion li:target > div {
  display: block;
}

/*Toggle open and close links*/
#accordion li:target > a.open {
   display:none;
}

#accordion li:target > a.close {
   display:block;
}
   	

#accordion a {
  cursor: pointer;
  display: inline-block;
  width: 750px;
  background: #ffffff;
  color: #ff6600;
  font-family: open sans;
  border: 1px solid #ff6600;
  font-size: 24px;
  padding: 25px 20px;
  margin: 0px;
  text-decoration:none;
}

#accordion div {
  width: 750px;
  background: white;
  border: 1px solid gray;
  padding: 15px 20px;
}

#accordion li {
  list-style: none;
}
div.scroll {
  max-height: 1050px;
  overflow: auto;
}
.timely-stream:not(.timely-agenda) .timely-event {
  min-height:92px; !important
}
<ul id="accordion">
<li id="section1">
<a href="#section1" class="open">OneHockey</a>
<a href="#" class="close">OneHockey</a>
<div ><a href="https://imgur.com/HJwXuym"><img 
src="https://i.imgur.com/HJwXuym.png?1" width="750px" height="422px" 
title="source: imgur.com" /></a></div>
</li>
<li id="section2">
<a href="#section2" class="open">TOURNAMENTS</a>
<a href="#" class="close" >TOURNAMENTS</a>
<div class="scroll" >
<script src="//dashboard.time.ly/js/embed.js" data- 
src="https://events.time.ly/hye2ww2?categories=21029&organizers=43496" 
data-max-height="0" id="timely_script" class="timely-script"></script>
</div>
</li>
<li id="section3">
<a href="#section3" class="open">INFO</a>
    <a href="#" class="close">INFO</a>
<div >Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
</li>
<li id="section4">
<a href="#section4" class="open">STANDINGS/SCHEDULE</a>
    <a href="#" class="close">STANDINGS/SCHEDULE</a>
<div >Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
</li>
</ul>

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

What causes the error message 'avoid pushing route with duplicate key' when using NavigationStateUtils in React Native?

Within my React Native + Redux project, I have set up a reducer for navigation utilizing NavigationStateUtils: import { PUSH_ROUTE, POP_ROUTE } from '../Constants/ActionTypes' import { NavigationExperimental } from 'react-native' impo ...

Issue encountered while trying to interpret Bootstrap 4 within Netbeans 8.2

Currently, I am working on an HTML5/JS application using Node.js in Netbeans 8.2. As I develop the welcome page, I intend to incorporate Bootstrap 4. However, when I attempt to add bootstrap.min.css to my stylesheets folder, I encounter an error as shown i ...

What is the best way to keep the textfield value at 0? If you clear the textfield, it will result in another value being

If I don't input anything in this field, the total will show as isNaN, and I want to prevent form submission if it is isNaN. How can I stop the form from being submitted when the total value is isNaN? export default function BasicTextFields() { cons ...

Customizing the size of dateBox icons in JQuery Mobile

Is there a way to increase the button size within the input box of a dateBox? Currently, it appears small and difficult to click accurately. Additionally, it would be beneficial if clicking anywhere in the input field could open the calendar, instead of ju ...

Exploring jQuery Mobile - What Causes an Empty State?

Using $.mobile.navigate("#test-page", {id:123}) for navigation to a secondary page seems to be successful. The transition between pages is smooth.... but the state remains empty! According to the documentation, the state should contain all necessary info ...

What factors influence Redux in determining when to update the user interface?

As per the design, when the state updates, the UI should also update accordingly. However, if I return a completely new object, it seems to have no effect on the UI. case 'clearArticleForm': let newState1 = {}; return newState1; } E ...

Tips on creating a responsive div element within the viewport?

I have a variety of nested div elements within a parent div, set up like this: #mycontent > div { width: 14.28%; } <div id="myheader">some header content</div> <div class="container" id="mycontent"> <div class="outerdiv" id= ...

When switching back to the parent window and attempting to execute an action, a JavaScript error is encountered

Currently automating a SnapDeal eCommerce website A challenge I am facing is an error message in the console: The issue occurs when transitioning from a child window back to the parent window and performing operations on the parent window. //Automa ...

Generating HTML tables with charts using FireFox

I am encountering an issue: My table contains charts and tables that are displayed correctly in browsers. However, when I attempt to print it (as a PDF) in Mozilla Firefox, the third speedometer gets cut off, showing only 2.5 speedometers. Using the "s ...

Unable to correctly declare and display UTF-8 character within JSON syntax

In my JSON object, there is an attribute that contains a unique special character - I've attempted to save the string in encoded UTF-8 as "\xF0\x9F\x94\x94" or tried displaying it using its HEX value - String.fromCharCode(0x1F514 ...

Using the HTML <span> and svg elements together does not allow them to be inline with each other

In my current scenario, I have a fieldset that is inline with another one on the page. The specific fieldset in question contains an SVG circle and some text. My objective is to have both elements inline with each other, while allowing the fieldset to adj ...

Ensure that the form is submitted only after confirming it in the modal with react-hook-form

**I am facing an issue with submitting react-hook-form on confirm in a modal component. Whenever the user selects confirm, I need the form to be submitted directly. I have tried writing the modal inside FormSubmitButton. Also, I have tried placing it insi ...

jsp fullcalendar select not functioning properly

The code snippet for the select: function within fullcalendar is as follows: select: function(start, end, jsEvent, view) { if (start.isBefore(moment())) { $('#calendar').fullCalendar('unselect'); return false; } else { //ajax Cal ...

Adjust div height to match the dynamic height of an image using jQuery

I'm facing an issue with my image setup. It has a width set to 100% and a min-width of 1024px, but I can't seem to get the 'shadow' div to stay on top of it as the window size changes. The height of the shadow div also needs to match th ...

How can we avoid excessive re-rendering of a child component in React when making changes to the parent's state?

In my React application, I am facing a situation where a parent component controls a state variable and sends it to a child component. The child component utilizes this state in its useEffect hook and at times modifies the parent's state. As a result, ...

What could be the reason the background-color isn't changing when I apply button:hover?

body{ font-family:"Arial","Lucida Grande", "Lucida Sans Unicode", Verdana, Helvetica, sans-serif; font-size:12px; } p, h1, form, button{border:0; margin:0; padding:0;} .spacer{clear:both; height:1px;} /* ----------- My Form ----------- */ .myform{ margin:0 ...

Tips for integrating CSS with Material UI TableContainer

I have utilized Material UI Grid to display data in a chart. However, the appearance of the chart does not match my expectations. Instead of resembling the desired "dense table," it looks different: Actual Look of the Chart Below is the code snippet I ha ...

Vuetify: How to restore the input value in v-text-field

This app is designed with a simple v-text-field for user input. The issue I am facing is that when I enter a combination of numbers and letters like 11a, then quickly tab out or click out of the input field before losing focus, it only shows 11. However, ...

SwiperJS continuously applies additional right margin to every slide

My Swiper carousel seems to be adding an unnecessary 5px margin-right to each slide, resulting in the cards not fitting into one frame. https://i.sstatic.net/fwn5G.png I attempted to fix this by setting the margin-right to 0px for the .swiper-slide class ...

Is it possible to set all UI forms to a readonly/disable mode?

We have a specific requirement where, if the user's access level is set to "READ ONLY", all form input elements should be made readonly. Our coding approach involves using a template HTML that contains widgets which are referenced in the correspondin ...