Creating an Accordion with HTML, CSS & jQuery

An accordion is usually associated with FAQ areas. If printed to the page, FAQs could stop users from finding the answers they’re after due to all the text they’re presented with.

That’s a good argument as they show a simple outline of the content. Imagine browsing an FAQ and you had to scroll all the way down through loads of sections to find the answer, it would be a painful. If you could simply scroll the titles and have the content hidden, it would allow you to scan much faster, therefore giving a 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

When coding up components I like to follow the BEM structure. Some of you will notice it’s not actual BEM. That’s because I follow a basic principle which uses nested-naming. For example, the entire element has an .accordion-section inside it, which is then followed by an .accordion-section-title.

This approach can have its drawbacks, yet I’ve found it to be sustainable on larger projects because it makes me think about how many elements I’m nesting and if it’s necessary.

It also keeps my Sass organised, therefore it avoids too much nesting and keeps things readable.

<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

There are a few things going on here. First of all, see the overflow:hidden; on the main element. This is done to give the rounded corners effect on the sections, yet stop things hanging over the edge.

I’ve used comments to indicate where any type styling is placed. I do this on all projects to keep things organised. In Sass, 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 CSS.

/*----- 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 a best practice to outline the code you’re going to write before you start, especially with something like JS.

Here is the code we need and in this case, we would write it out in a procedural fashion, then move on to making it more modular. As a result, we get the following two examples:

$(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
	});
});
$('.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 we can move on to the modular 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');
}

Accordion Conclusion

In conclusion, they can be very useful, as I said in the intro. However, be aware they should only be used in cases where they’re beneficial, as is the case with any component.

By improving your code as you go, you’ll learn to just make it modular from the start.

If you have any questions or comments just leave a comment below!

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


Comments

Leave a Comment

Comments (195)

Larry

June 3, 2016 at 1:27 pm

GREAT piece of code here!!!

I am trying to load a table inside my accordion-content section but in order to do that I need to pass a value with the links href.

What I have done is to make my section-title include the table headers. These headers refer to invoices. Now when I click on the appropriate header I would like the invoice number to be passed to the href so the proper invoices shows in the accordion.

Am I wasting time or can this be done???

Reply

Caro

May 26, 2016 at 8:04 pm

Iā€™m struggling to get the accordion to work. I was able to successfully modify the CSS to my liking; however, when I click on each accordion section title, nothing happens.
I added this before the jQuery in the head.

<br />
&lt;script type=&quot;text/javascript&quot; src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js&quot;&gt;&lt;/script&gt;<br />
	&lt;script type=&quot;text/javascript&quot; src=&quot;accordion.js&quot;&gt;<br />

Iā€™m stuck. Thanks for your help.

Reply

Caro

May 26, 2016 at 8:03 pm

I’m struggling to get the accordion to work. I was able to successfully modify the CSS to my liking; however, when I click on each accordion section title, nothing happens.
I added this before the jQuery in the

I’m stuck. Thanks for your help.

Reply

Ace

May 19, 2016 at 12:06 pm

It doesn’t work for me. The jquery part doesn’t seem to function. I can see the accordion menu with the styling but no jquery. I have just copied your codefrom the demo basically under the part. Also included the script lines in the header. Please help. Respond to my email.

Reply

Julie

May 11, 2016 at 7:50 pm

Hi. Thank you for the code. It’s working great. However, now my main menu above it is not bringing up my dropdown on hover. Any suggestions for things I can check? šŸ™‚

Reply

sreedhar

May 10, 2016 at 8:03 am

hi i have more than one accordian in my web page

when i open first one its opening and when i open a second one the first one is not closing

when i close any one of them then both are closing.

how to close a previously opened one when opening a new one

Reply

Tammy

April 20, 2016 at 11:17 pm

OMG.. i’m trying to add this to my godaddy.com website builder. it is so stupid.. the only thing I can do is add html code with a little box they provide to enter code. i’m not familiar with any code at all.. but i’m going to assume the html code is the basic setup .. and the javascript part is the extra bells and whistles it does (like opening the answer when the question is clicked), and the CSS is the format of the text, colors, etc? is that right? anyways.. the javascript and the CSS portion isn’t happening. when previewed, that portion of the code I pasted in… shows up as plain text. any idea what i’m doing wrong? GoDaddy webuilder will not help me at all. I can screenshot some things to you if you want.
Tammy

Reply

Jo

April 19, 2016 at 4:21 pm

Hi,
thanks for this great accordion – i got all working allright but somehow the accordion starts with open sections instead of being closed first. Do you have any ideas which could be the cause of this – i did remove media queries as i had that as a problem before but now this doesnt do it either.
I would appreciate your assistance here greatly.

Regards Jo

Reply

Nelly

April 14, 2016 at 9:58 pm

Hey! Really nice tutorial!
Just one question: One of my section is really long so I have to scroll a bit. But when I open an other section, which is quite shorter, the browser doesn’t go to the start of this section but stays on the same position as it was when the long section was opened.
How do I get the browser always go to the start of the active section?
Thanks in advance!
Nelly

Reply

cory

March 7, 2016 at 4:07 pm

Can anyone please tell me how to add more rows in this project?
Thanks!

Reply

TDP

April 18, 2016 at 5:02 pm

<br />
      &lt;div class=&quot;accordion-section&quot;&gt; &lt;a class=&quot;accordion-section-title&quot; href=&quot;#accordion-addnumber&quot;&gt;Learning Center&lt;/a&gt;<br />
      &lt;div id=&quot;accordion-addnumber&quot; class=&quot;accordion-section-content&quot;&gt; &lt;img src=&quot;/images/logo-clc-01.png&quot; /&gt; &lt;/div&gt;<br />
      &lt;!–end .accordion-section-content–&gt;<br />
    &lt;/div&gt;  
To add rows..just add the div and increase the number of that div. Mines has 10…so if I wanted to add a row, the next number would read “11” where “addnumber” is.

Reply

cory

March 4, 2016 at 8:17 pm

Hello,
First off, well done with styling and functionality of this accordion, however I’m trying to incorporate it into my project an was wondering if I could modify it so that when a user clicks on the tabs they can open an close independently of each other?
in another words if you click one it opens but when I click on the next one that one closes and the other opens, I would like to modify so that you could have them all open at the same time and close one at a time.. Make sense?

Thanks in advance
Cory

Reply

Naveen

March 2, 2016 at 11:31 am

This is awesome tutorial for me. I’m a beginner in script language. Can you explain how can we expand the first element as default. Now all the elements are closed. I need the first item opend. Can you help me to do this???

Thank you…

Reply

Tizian

April 29, 2016 at 2:08 pm

try this in your css:


#accordion-1.accordion-section-content {
display:block;
}
Reply

cosmos

September 9, 2016 at 4:43 am

this code good. but click the title of opened section then this section content div close and open again.
How can i fix this?

Reply

Konto

February 20, 2016 at 4:03 pm

Thanks for this post!
But whats more interesting to me is not your post content, it’s the syntax highlighting in the code boxes – thats actually pretty cute!! šŸ™‚

Reply

Marie

February 17, 2016 at 7:36 am

Wonderful simple script šŸ™‚

Is it possible to open and close all accordions with one link (like “View all”)?

Best Regards
Marie

Reply

G

February 15, 2016 at 7:44 pm

Does anyone know how to add a small image to the expanded text within an accordion? I want to include a thumbnail.

Reply

Luc

February 6, 2016 at 11:52 pm

Hi Seb. Great article. The accordion works great!

I have an UX isssue though. I have created 6 accordions and under each, there is LOTS of content. The problem I am facing is that when the user gets to the bottom of, say, accordion 4 and opens accordion 5, this action pushes everything up (as the previous accordion closed, leaving the user in the middle of the new open section (accordion 5)

Is any way to reposition the screen to the beginning of the open accordion?, or, have multiple accordions open??

I look forward your (and everyone else’s) input šŸ™‚

Many thanks!

Reply

Chris

May 8, 2016 at 2:14 pm

I’m also having this issue, did you find an answer? The user has to scroll up to collapse/select a new tab.

Reply

Nicole

June 30, 2016 at 8:12 pm

I think I’ve found a way to do that in the Jquery. I’ve copied the initial line where I’ve added “scrollToHeading”.

$(‘.accordion ‘ + currentAttrValue).slideDown(300, scrollToHeading).addClass(‘open’);
}
e.preventDefault();

function scrollToHeading(){
$(‘html, body’).animate({
scrollTop: $(‘.active’).first().offset().top
})
}
});
});

It worked for me – if you’d like more specific information check out this page where
https://www.sitepoint.com/community/t/jquery-accordian-want-to-always-start-at-top-of-section/110230

Reply

Andy

February 2, 2016 at 2:23 am

I see a comment/question about nesting accordions but didn’t see a response. I too would like to nest accordions. Is there a solution for this request? Love how simple and easy this is to use ā€” thank you for sharing!

Reply

Mike Aubart

January 29, 2016 at 2:35 pm

Thank you so much! This is perhaps the best tutorial I’ve encountered on the web. It’s clear, informative, and very well presented and organized. Very much appreciated!!!

Reply

Tom

January 28, 2016 at 3:10 pm

Hi Again,
I figured out the problem. Your code uses the “href” as a variable. This was causing my page to jump to the target ID with the same name. I changed the variable name to “aref” and it works perfect now.

Reply

Tom

January 27, 2016 at 11:42 pm

I figured out what is happening with the scroll. The code is moving the browser window in an effort to have the first line of the open content box at the top. I don’t want this. What code can I modify to have it not move the browser window.

Thanks for a nice piece accordion BTW

Reply

Tom

January 27, 2016 at 10:33 pm

I used your code and it functions, however, whenever you click a title its scrolls my whole browser window down as it opens and closes the hidden . I have tried to trouble shoot but I can’t find the issue. Any thoughts?

Reply

JR

January 27, 2016 at 12:53 pm

I am having problems closing an open accordion section. Currently if i click on an open title, it will close and reopen the same section again. I would like the accordion to be able to close. So if it is open once you click on it it will go back to closed.

Also is there a way to make an external button in the end of a long section to close the section?

Reply

JR

January 26, 2016 at 3:01 pm

Hello,

I am trying to add an external close button inside bottom the accordion sections.
Also is it possible to close the section after clicking on the open section title. Currently it just reopens the section again.

Reply

tomas

January 22, 2016 at 9:33 am

i just added posibility to open element by url hash, or if not defined url hash, default open first accordion element:


if (window.location.hash) {
$(‘a.accordion-section-title[href="’+window.location.hash+’"]’).trigger(‘click’);
} else {
$(‘a.accordion-section-title[href="’+ $(‘a.accordion-section-title:first’).attr(‘href’) +’"]’).trigger(‘click’);
}

Reply

Xelipher

January 8, 2016 at 8:49 am

Ugh, I’m new to HTML.. I like exactly what’s here. But How do I actually piece it all together?
I love what shows in the demo. I usually learn off other code and see what it’s saying. I use http://i.stack.imgur.com/oslRB.png to paste the HTML code into, and sometimes it doesn’t work. Is there anything else I could use to “emulate” what code i put in to see if it works?

Thanks, sorry.

Reply

Daniel

January 6, 2016 at 3:17 pm

Thank you for this excellent example
When I add more accordions by copy/paste they are outside the box and do not work
How do I extend this function?
thanks

Reply

mallikarjuna

January 4, 2016 at 9:00 am

i want to put the button in the accordion when click on the button it has to redirect to the next page

Reply

Teena

January 1, 2016 at 1:13 pm

This article is wonderful.
https://inspirationalpixels.com/tutorials/creating-an-accordion-with-html-css-jquery

I am trying to use this functionality but struggling with changing the Color(Black) of the Accordion Section. I can’t find the css also where it is defined. Please help me in that

Reply

Aamer

December 16, 2015 at 12:37 pm

Thanks a lot for this example
If I want to make the first section open what should I do?
Thanks for your help in advance

Best Regards
Aamer

Reply

Malteras

January 5, 2016 at 12:47 pm

In your HTML file you’ll need to add ‘open’ to class=”accordion-section-content” in . It will look like this .

Also, in SCSS file, you will have to add style for your ‘.open’ class. It should look something like this:


.accordion-section-content {
padding:15px;
display:none;
&.open {
display: block;
}
}

Additionally, you can place class ‘active’ in

<br />
&lt;a href=&quot;#accordion-1&quot; rel=&quot;nofollow&quot;&gt;<br />

from your HTML.
I hope this helps.

Reply

ayman

December 9, 2015 at 11:03 am

i need to add read more link in the end of paragraph, how i do that ??

Reply

Krystian Jurkowski

December 3, 2015 at 5:06 am

Your article here is excellent:
https://inspirationalpixels.com/tutorials/creating-an-accordion-with-html-css-jquery

When I try to implement the design, the text and all comes up on the page, but it is not interactive and in an accordion like it is supposed to be. I suspect maybe it is not connecting to the javascript file? Or any other tips on why it may be like this? The website looks like this right now:

Reply

Nicole Langarica

December 12, 2015 at 12:36 am

I Absolutely love this style! I am having the same hiccup as Krystian. I can’t seem to get this interactive. Could you help?

google.load(“jquery”, “1.3.2”);

$(document).ready(function() {
functionclose_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
varcurrentAttrValue = $(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();
});
});

/*—– 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.500em;
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;
}




Goal I

Implementation, support, and monitoring of the Common Core State Standards (CCSS)
Initiatives
1: Focus on accountability measures that support Common Core State Standards and writing across the curriculum (Smarter Balanced Assessments, college and career readiness measures)
2: Monitor and provide support in the implementation of the Program Improvement model at all schools
3: Support programs to meet the instructional needs of all students, including International Baccalaureate, Advanced Placement, Gifted and Talented Education, Advancement Via Individual Determination, Dual Immersion, and Science/Technology/Engineering/Math (STEM)

Goal II

Maintain a safe environment for students and staff
Initiatives
1: Develop and implement an articulated plan to prevent truancy and chronic absenteeism, and reduce suspension and expulsion rates
2: Collaborate with the police departments of Fairfield and Suisun City regarding student safety and development of the Sullivan Interagency Youth Services Center
3: Strengthen and increase counseling services for students

Goal III

Maintain fiscal solvency, liquidity, and effective use of District resources
Initiatives
1: Implement and monitor the Local Control Accountability Plan (LCAP) based on district spending priorities
2: Continue to develop strong working relationships with all employee associations
3: Utilize technology to become more cost effective, efficient, and environmentally friendly

Goal IV

Maintain positive District and community relations
Initiatives
1: Promote active engagement of parents and the community through a variety of communication strategies
2: Continue to hold Superintendent Open Forums with staff at each school site and location within our District to engage in open, honest dialogue and information sharing
3: Continue to foster partnerships with the city leadership from Fairfield and Suisun City to support all schools in the district

Goal V

To function as a continually effective Governance Team
Initiatives
1: Continue to provide professional information presentations at Study Sessions for the Board
2: Continue the work of the Governance Subcommittee to update policies and revise Board self-evaluation tools, as well as develop strategies to improve the effectiveness of the Governance Team
3: Continue to operate openly with trust, integrity, and respect for each other

Thank you!

Reply

Hamed Salehi

November 23, 2015 at 8:05 am

Very Useful & Perfect ….Thanks

Reply

Ramesh

November 20, 2015 at 11:10 am

how to default open first element of accordion.

Thanks
Ramesh Pal

Reply

Ian Porrat

November 18, 2015 at 12:11 pm

Thanks man! Very simple and functional.

I changed some stuffs on the script, but this was very helpfull!

Reply

Kai

October 22, 2015 at 3:46 pm

Hi Seb, awesome work!

Finally got it working. But now I’ve got another question. Do you know how to keep a section opened when reloading the page? That would be really awesome!

Thank you!

Regards
Kai

Reply

Alice

October 21, 2015 at 2:32 pm

Hello, I hope you are well.

I tried the code and it really did not work.

What did I do wrong I wonder?

<br />
        &lt;a href=&quot;#accordion-1&quot; rel=&quot;nofollow&quot;&gt;Accordion Section #1&lt;/a&gt;</p>
<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.<br />
        &lt;!–end .accordion-section-content–&gt;<br />
    &lt;!–end .accordion-section–&gt;<br />
&lt;!–end .accordion–&gt;</p>
<p>        &lt;a href=&quot;#accordion-1&quot; rel=&quot;nofollow&quot;&gt;Accordion Section #1&lt;/a&gt;</p>
<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.<br />
        &lt;!–end .accordion-section-content–&gt;<br />
    &lt;!–end .accordion-section–&gt;<br />
&lt;!–end .accordion–&gt;<br />
Reply

Kai

October 21, 2015 at 11:01 am

Great work!

But for me it’s actually not working :/ I don’t know whats wrong with it. Just tried to copy an dpaste to jsfiddle. But it’s not working :/ Hope you can help me!

https://jsfiddle.net/cgg4o8xm/

Thanks
Kai

Reply

Stefan

January 14, 2016 at 1:45 am

Hey,

Your issue is that you need to update the Javascript framework to jQuery 2.1.3.

It works for me when I update it.

Reply

Stefan

January 14, 2016 at 8:09 pm

Hey,

You just need to update the javascript framework in your jsfiddle to jQuery (its currently No Library(pure JS)).

Stefan.

Reply

luke

January 20, 2016 at 5:03 pm

You forgot to include jquery stuff like : https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js in meta

Reply

Joseph Beaumont

September 30, 2015 at 12:11 am

Hey! Awesome website and it has really helped me learn a lot.

I am attempting to use your ‘Creating an Accordion with HTML, CSS & jQuery’ code and everything is working fantastically, however, it seems when I click to expand/collapse the same section in the accordion, it automatically pops back open. Any idea why this would happen?

Thanks,
Joseph

Reply

Siddarth Sharma

September 27, 2015 at 3:02 am

Great Article ! Thanks , Just the thing I was Looking For ! Thanks Again !

Reply

Amval

November 22, 2015 at 9:14 am

The problem is that if you click on the span, the event is triggered on this element, and thus all the remaining code, based on the event target, will not work.
A workaround would be to define the targets differently.

<br />
$(‘.accordion-section-title’).click(function(e) {<br />
        // Grab the &lt;a&gt; element of the section title<br />
        var currentAttrValue = $(this).closest(‘.accordion-section-title’);<br />
        // Test on the link (and not on the span!)<br />
        if(currentAttrValue.hasClass(‘active’)) {<br />
            close_accordion_section();<br />
        }else {<br />
            close_accordion_section();<br />
            // Add active class to section title<br />
            currentAttrValue.addClass(‘active’);<br />
            // Open up the hidden content panel<br />
            $(‘.accordion ‘ + currentAttrValue.attr(‘href’)).slideDown(300).addClass(‘open’);<br />
        }<br />
        e.preventDefault();<br />
    });<br />
Reply

Barney

September 16, 2015 at 12:12 am

Hello

Your article here is excellent:
https://inspirationalpixels.com/tutorials/creating-an-accordion-with-html-css-jquery

I just have one suggestion. As an amateur, it would have benefitted me to have one sentence in there that says something like:
“Don’t forget to add to your header”
I know this is a basic thing to do, but since your article is written very well and therefore may be used by other web design hobbyists like myself, the chances are they might need reminding too.

Thought I’d make the suggestion anyway.

Thanks for the online help!
Barney

Reply

Aaron

August 28, 2015 at 6:33 pm

Hi!

I really like your awesome tutorial. I’ve managed to make the first accordion always active by adding: display:block; which works fine. I was just wondering, as a beginner about the nesting. How can I nest several accordions? I mean, I’ve tried it, but when I click on any nested accordion, it just collapses to the parent accordion. Like a Shy plant šŸ™‚ (https://www.youtube.com/watch?v=DF-b6TsO1DM&noredirect=1).

Any help is greatly appreciated. Thanks.

Reply

dante

August 25, 2015 at 1:39 pm

if you want to make any tab open by default, just add this to you code before the event

var activeopen = $(‘.accordion .accordion-section-title.active’);
$(‘.accordion ‘ + activeopen.attr(‘href’)).show();

will open any tab that has the active class on it on page load

Reply

Monica

August 21, 2015 at 8:42 am

Hi,

The accordion jQuery is very easy and flexible. Thanks for sharing.

I have created almost 25 accordions. My requirement is in a form on select box value change I want to hide few accordions on page load.

Reply

Simon

August 12, 2015 at 9:49 pm

Hi,
Accordion is lightweight and great to use.
I’d really like to see support for ‘deep linking’ (linking to a particular tabs contents from another location). It would be great if you could suggest how to do this?
Cheers

Reply

Jonas

August 3, 2015 at 5:26 pm

Thank you very much – great job!

Reply

Jesse

July 23, 2015 at 10:29 pm

To add additional accordion sections, I copy paste the following code and change the section number/ID to the next sequential value (4, 5, 6, etc.). The first three sections work. New sections added do not work. When clicked, it stays highlighted and never expands to show the content. Am I missing some critical step? Do I need to go into the .js or css files and add some sort of reference? BTW, I have almost no experience with HTML, CSS, JQuery, so apologies for my ignorance! For the three sections that do work, looks GREAT! So thanks for that!

<br />
&lt;div class=&quot;accordion-section&quot;&gt;<br />
	&lt;a class=&quot;accordion-section-title&quot; href=&quot;#accordion-4&quot;&gt;Accordion Section #4&lt;/a&gt;<br />
	&lt;div id=&quot;accordion-4&quot; class=&quot;accordion-section-content&quot;&gt;<br />
		&lt;p&gt;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.&lt;/p&gt;<br />
	&lt;/div&gt;&lt;!–end .accordion-section-content–&gt;<br />
&lt;/div&gt;&lt;!–end .accordion-section–&gt;<br />
Reply

Niall

July 22, 2015 at 2:17 pm

Anyone able to give me a hand? I have added the code correctly but my accordion seems to be acting a bit weird.

www.24tees.co.uk/FAQ

I have changed the variable names etc to avoid conflicts with other JS/JQuery, not sure why it isn’t working. Much appreciated if you can take a look šŸ™‚

Reply

Niall

July 24, 2015 at 10:53 am

Fixed the issue, simply changed ‘href’ to ‘id’ in the JS and HTML.

Reply

Simone

July 17, 2015 at 1:07 pm

How can add a “font awesome” icon?
I will want add a arrow icon…any idea?

Reply

Inspirational Newsletter


Join the newsletter to get the best articles, tutorials and exclusive freebies every two weeks.

No spam. You can unsubscribe at any time.