3

I'm super new to JS but I wanted a really simple accordion so I built one. For some reason I am at a loss when trying to add an easing effect to the opening / closing of it. Any help would be much appreciated. Thank you!

CodePen of Accordion

js code:

(function(){
// This class will be added to the expanded item
var activeItemClass = 'accordion-expanded';
var accordionItemSelector = '.accordion-section';
var toggleSelector = '.accordion-head';

$(toggleSelector).on('click', function() { 

    $(this)
        .closest(accordionItemSelector) // go up to the accordion item element
        .toggleClass(activeItemClass)
            .siblings()
            .removeClass(activeItemClass);
});

})();
WhiteHat
  • 59,912
  • 7
  • 51
  • 133
reidb
  • 267
  • 2
  • 8

2 Answers2

0

Since you're using jQuery, why not this:

var accordionItemSelector = '.accordion-body';
var toggleSelector = '.accordion-head';

$(toggleSelector).on('click', function() { 
  if (!$(this).next(accordionItemSelector).is(":visible"))
    $(toggleSelector).not($(this)).next(accordionItemSelector).slideUp();
  $(this).next(accordionItemSelector).slideToggle();   
});

UPDATED PEN

Batu.Khan
  • 3,060
  • 2
  • 19
  • 26
0

Here is working code for accordion :-

$(document).ready(function(){
 $('.item').click(function (){
   if($(this).next('.item-data').css('display') != 'block'){
     $('.active').slideUp('fast').removeClass('active');
     $(this).next('.item-data').addClass('active').slideDown('slow');
    } else {
     $('.active').slideUp('fast').removeClass('active');
    }
 });
});   

and HTML

<div class='container'>
<div class='item'>Item 1</div>
<div class='item-data'>
    <div>
        This is the content for Accordion 1
    </div>
</div>
<div class='item'>Item 2</div>
<div class='item-data'>
    <div>
        This is the content for Accordion 2
    </div>
</div>
<div class='item'>Item 3</div>
<div class='item-data' >
    <div>
        This is the content for Accordion 3
    </div>
</div>
<div class='item'>Item 4</div>
<div class='item-data' >
    <div>
        This is the content for Accordion 4
    </div>
</div>

CSS

<style type="text/css">
.container
{
    display:block;
    width: 500px;
    height : auto ;
    margin: 0 auto;
}
.item
{
    display : block;
    width : inherit ;
    height : 40px;
    line-height : 40px;
    background : #555 ;
    border: 1px solid #000 ;
    cursor: pointer;
    color: #fff;
}
.item-data
{
    display : none ;
    width : inherit ;
    height : auto ;
    border: 1px solid #ccc;
}
.active {
    background : #eee ;
    color : #000 ;
}
.item-data div{
    margin: 30px;
}
</style>
Anand Deep Singh
  • 2,560
  • 3
  • 22
  • 28