Free Web Design Code & Scripts

jQuery Accordion Open and Close on Click

jQuery Accordion Open and Close on Click
Code Snippet:A simple jQuery Accordion with unlimited nesting
Author: Brenden Palmer
Published: 3 weeks ago
Last Updated: 3 weeks ago
Downloads: 73
License: MIT
Edit Code online: View on CodePen
Read More

Are you looking to present information cleanly and save screen space on your website? An accordion component is a fantastic way to achieve this. This tutorial will guide you through creating a dynamic content section. You will learn how to implement a fully functional jQuery Accordion that opens and closes on click. This solution is perfect for FAQs, product features, or any list of items where you want to reveal details on demand.

1. Create the HTML Structure

First, you need to set up the basic layout for your accordion. This HTML code defines the main accordion container and its individual items. Each item has a toggle link and an inner content area.

<h1>A Cool Accordion</h1>

<p class="description">
  You could simply toggle the .show class (if display: block is uncommented in the CSS) in JavaScript, but you'll lose the animation.
</p>

<ul class="accordion">
  <li>
    <a class="toggle" href="javascript:void(0);">Item 1</a>
    <ul class="inner">
      <li>Option 1</li>
      <li>Option 2</li>
      <li>Option 3</li>
    </ul>
  </li>
  
  <li>
    <a class="toggle" href="javascript:void(0);">Item 2</a>
    <ul class="inner">
      <li>Option 1</li>
      <li>Option 2</li>
      <li>Option 3</li>
    </ul>
  </li>
  
  <li>
    <a class="toggle" href="javascript:void(0);">Item 3</a>
    <ul class="inner">
      <li>
        <a href="#" class="toggle">Open Inner</a>
        <div class="inner">
          <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tempus placerat fringilla. Duis a elit et dolor laoreet volutpat. Aliquam ultrices mauris id mattis imperdiet. Aenean cursus ultrices justo et varius. Suspendisse aliquam orci id dui dapibus
            blandit. In hac habitasse platea dictumst. Sed risus velit, pellentesque eu enim ac, ultricies pretium felis.
          </p>
        </div>
      </li>
      
      <li>
        <a href="#" class="toggle">Open Inner #2</a>
        <div class="inner">
          <p>
            Children will automatically close upon closing its parent.
          </p>
        </div>
      </li>
      
      <li>Option 3</li>
    </ul>
  </li>
  
  <li>
    <a class="toggle" href="javascript:void(0);">Item 4</a>
    <ul class="inner">
      <li>
        <a href="#" class="toggle">Technically any number of nested elements</a>
        <ul class="inner">
          <li>
            <a href="#" class="toggle">Another nested element</a>
            <div class="inner">
              <p>
                As long as the inner element has inner as one of its classes then it will be toggled.
              </p>
              <p>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tempus placerat fringilla. Duis a elit et dolor laoreet volutpat. Aliquam ultrices mauris id mattis imperdiet. Aenean cursus ultrices justo et varius. Suspendisse aliquam orci id dui dapibus
                blandit. In hac habitasse platea dictumst. Sed risus velit, pellentesque eu enim ac, ultricies pretium felis.
              </p>
            </div>
          </li>
        </ul>
      </li>
      
      <li>Option 2</li>
      
      <li>Option 3</li>
    </ul>
  </li>
</ul>

2. Style the Accordion with CSS

Next, apply these CSS rules to style your accordion. This styling will ensure it looks good and hides the inner content by default. It also includes styling for the toggle links and general page elements, including font imports.

@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 300;
  font-stretch: normal;
  src: url(https://fonts.gstatic.com/s/opensans/v44/memSYaGs126MiZpBA-UvWbX2vVnXBbObj2OVZyOOSr4dVJWUgsiH0B4gaVc.ttf) format('truetype');
}
@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  font-stretch: normal;
  src: url(https://fonts.gstatic.com/s/opensans/v44/memSYaGs126MiZpBA-UvWbX2vVnXBbObj2OVZyOOSr4dVJWUgsjZ0B4gaVc.ttf) format('truetype');
}
@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 600;
  font-stretch: normal;
  src: url(https://fonts.gstatic.com/s/opensans/v44/memSYaGs126MiZpBA-UvWbX2vVnXBbObj2OVZyOOSr4dVJWUgsgH1x4gaVc.ttf) format('truetype');
}
@font-face {
  font-family: 'Pacifico';
  font-style: normal;
  font-weight: 400;
  src: url(https://fonts.gstatic.com/s/pacifico/v23/FwZY7-Qmy14u9lezJ-6H6Mw.ttf) format('truetype');
}
* {
  box-sizing: border-box;
  font-family: 'Open Sans', sans-serif;
  font-weight: 300;
}
a {
  text-decoration: none;
  color: inherit;
}
p {
  font-size: 1.1em;
  margin: 1em 0;
}
.description {
  margin: 1em auto 2.25em;
}
body {
  width: 40%;
  min-width: 300px;
  max-width: 400px;
  margin: 1.5em auto;
  color: #333;
}
h1 {
  font-family: 'Pacifico', cursive;
  font-weight: 400;
  font-size: 2.5em;
}
ul {
  list-style: none;
  padding: 0;
}
ul .inner {
  padding-left: 1em;
  overflow: hidden;
  display: none;
}
ul .inner.show {
  /*display: block;*/
}
ul li {
  margin: 0.5em 0;
}
ul li a.toggle {
  width: 100%;
  display: block;
  background: rgba(0, 0, 0, 0.78);
  color: #fefefe;
  padding: 0.75em;
  border-radius: 0.15em;
  transition: background 0.3s ease;
}
ul li a.toggle:hover {
  background: rgba(0, 0, 0, 0.9);
}

3. Include Necessary JavaScript Libraries

Before adding the custom script, you must include the jQuery library. This library provides the functionality needed for the accordion’s animations and interactions. Place this script link just before the closing </body> tag.

<script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

4. Add the JavaScript Logic

Finally, add the JavaScript code to make your accordion interactive. This script handles the click events on the toggle links. It ensures that when you click an item, its content slides open or closed. Also, it manages closing other open items when a new one is clicked, creating a clean accordion effect.

$('.toggle').click(function(e) {
  	e.preventDefault();
  
    var $this = $(this);
  
    if ($this.next().hasClass('show')) {
        $this.next().removeClass('show');
        $this.next().slideUp(350);
    } else {
        $this.parent().parent().find('li .inner').removeClass('show');
        $this.parent().parent().find('li .inner').slideUp(350);
        $this.next().toggleClass('show');
        $this.next().slideToggle(350);
    }
});

That’s all! You have successfully created a dynamic jQuery Accordion that opens and closes on click. This element enhances user experience by organizing content efficiently.

Related Code Snippets:

Loading... ...

Loading preview...

Device: Desktop
Dimensions: 1200x800
Lines: 0 Characters: 0 Ln 1, Ch 1

Leave a Comment

About W3Frontend

W3Frontend provides free, open-source web design code and scripts to help developers and designers build faster. Every snippet is reviewed before publishing for quality. Learn more.