accordion-thumb

Creating an Accordion with HTML, CSS & jQuery

In this tutorial, we going to make a jQuery accordion, built with HTML and CSS. If you get stuck, don’t hesitate to ask me a question.

They’re most commonly used in F.A.Q.’s where you have questions and answers. Which, if just displayed straight to the page could potentially become incredibly long, stopping users from actually wanting to read or finding the answer they’re looking for.

That’s a good argument for accordion components, as they allow users to see the outline of the content at a glance. Imagine if you were browsing a F.A.Q. and had to scroll all the way down through 20 different sections just to find your answer, it would be a nightmare. If you could just scroll through the titles with content temporarily hidden, then it would make for a much better experience.

You might also like: Creating Tabs with HTML, CSS & jQuery

Table of Contents

  1. Skip to The HTML
  2. Skip to The CSS
  3. Skip to The jQuery
Final result: Coded accordion with HTML, CSS and jQuery

1 The HTML Structure

Finished HTML

As you can see it’s a very simple piece of HTML. When coding up components like this I like to follow a BEM like structure. Some of you more experienced readers will notice it’s not actual BEM. I follow a basic principle, which is to use nested-naming. For example, the .accordion has an .accordion-section inside it, which is then followed by an .accordion-section-title.

This approach obviously has it drawbacks, like most things do, but I’ve found to be sustainable on larger projects because it makes me think about how many elements I’m nesting an whether it’s really necessary.

It also helps keep my Sass organised by avoiding to much code nesting.

<div class="accordion">
    <div class="accordion-section">
        <a class="accordion-section-title" href="#accordion-1">Accordion Section #1</a>
        
        <div id="accordion-1" class="accordion-section-content">
            <p>Mauris interdum fringilla augue vitae tincidunt. Curabitur vitae tortor id eros euismod ultrices. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Praesent nulla mi, rutrum ut feugiat at, vestibulum ut neque? Cras tincidunt enim vel aliquet facilisis. Duis congue ullamcorper vehicula. Proin nunc lacus, semper sit amet elit sit amet, aliquet pulvinar erat. Nunc pretium quis sapien eu rhoncus. Suspendisse ornare gravida mi, et placerat tellus tempor vitae.</p>
        </div><!--end .accordion-section-content-->
    </div><!--end .accordion-section-->
</div><!--end .accordion-->

2 The CSS Styling

Finished CSS

The first thing to note is the overflow:hidden; on the wrapping .accordion selector. This is done to give the rounded corners effect on the section links.

I’ve used code comments to indicate where any typographic styling is present, e.g. /* Type */. I do this on all my projects to keep the code organised. In Sass files I write it as // Type. When you leave a code comment in a Sass file with the two slashes it doesn’t show up in the compiled code.

/*----- Accordion -----*/
.accordion, .accordion * {
    -webkit-box-sizing:border-box; 
    -moz-box-sizing:border-box; 
    box-sizing:border-box;
}

.accordion {
    overflow:hidden;
    box-shadow:0px 1px 3px rgba(0,0,0,0.25);
    border-radius:3px;
    background:#f7f7f7;
}

/*----- Section Titles -----*/
.accordion-section-title {
    width:100%;
    padding:15px;
    display:inline-block;
    border-bottom:1px solid #1a1a1a;
    background:#333;
    transition:all linear 0.15s;
    /* Type */
    font-size:1.200em;
    text-shadow:0px 1px 0px #1a1a1a;
    color:#fff;
}

.accordion-section-title.active, .accordion-section-title:hover {
    background:#4c4c4c;
    /* Type */
    text-decoration:none;
}

.accordion-section:last-child .accordion-section-title {
    border-bottom:none;
}

/*----- Section Content -----*/
.accordion-section-content {
    padding:15px;
    display:none;
}

3 The jQuery Functionality

Finished jQuery

$(document).ready(function() {
    function close_accordion_section() {
        $('.accordion .accordion-section-title').removeClass('active');
        $('.accordion .accordion-section-content').slideUp(300).removeClass('open');
    }

    $('.accordion-section-title').click(function(e) {
        // Grab current anchor value
        var currentAttrValue = $(this).attr('href');

        if($(e.target).is('.active')) {
            close_accordion_section();
        }else {
            close_accordion_section();

            // Add active class to section title
            $(this).addClass('active');
            // Open up the hidden content panel
            $('.accordion ' + currentAttrValue).slideDown(300).addClass('open'); 
        }

        e.preventDefault();
    });
});

Code Outline/Setup

It’s usually a good practice to outline the code you’re going to write as you start, especially with something like jQuery, or plain JavaScript.

Here is my outline of the code we need:

$(document).ready(function() {
    function close_accordion_section() {
        // Close everything up
    }

    $('.accordion-section-title').click(function() {
        // Grab current anchor value
        var currentAttrValue = $(this).attr('href');

        // Open and close here
    });
});

Then I’ll add the code to get it working. In this case I would write it out in a procedural fashion and then move on to making it more modular, like so:

$('.accordion-section-title').click(function() {
    // Grab current anchor value
    var currentAttrValue = $(this).attr('href');

    $('.accordion .accordion-section-title').removeClass('active');
    $('.accordion .accordion-section-content').slideUp(300).removeClass('open');

    $(this).addClass('active');
    $('.accordion ' + currentAttrValue).slideDown(300).addClass('open'); 
});

From there I can move on to the re-usable version of the code by adding functions and so on:

function close_accordion_section() {
    $('.accordion .accordion-section-title').removeClass('active');
    $('.accordion .accordion-section-content').slideUp(300).removeClass('open');
}

That’s pretty much it. By improving your code as you go you’ll eventually learn to just make it re-usable and modular from the get-go.

If you have any questions then leave me a comment below!


Conclusion: Don’t Over-Use It

Accordions can be extremely useful, like I mentioned in the introduction. However, please be aware that they should only be used in cases where they’re actually beneficial, like any type of web component.

A lot of the time it seems cool and fun to use something like tabs, accordions, dropdowns etc… when all you need is a much simple solution. My advice when creating anything on the web is to start at the most basic level and work your way up.

You might also like: Create a Fading Popup Modal with jQuery

Follow IP on Twitter Like IP on Facebook

Advertisement