jQuery accordion - one open at a time

775 views Asked by At

I've got a accordion working with + and - images working when the accordion is opened and closed. I'm struggling to get it to only allow one open at a time.

(function ($) {
    $.fn.accordions = function (options) {
        return this.each(function () {
            var titleBar = $('.title', this),
                content = $('.content', this),
                img = $('<span class="arrow" />'),
                isClosed = content.hasClass('content');

            img.addClass((isClosed) ? 'upArrow' : 'downArrow');

            titleBar.append(img).on('click', function () {
                var parent = $(this).parents('.accordion'),
                    arrow = $('.arrow', this),
                    content = $('.content', parent);

                $(this).toggleClass('no-border');
                if (arrow.hasClass('upArrow')) {
                    content.slideDown(500);
                    arrow.removeClass('upArrow').addClass('downArrow');
                } else {
                    content.slideUp(500);
                    arrow.addClass('upArrow').removeClass('downArrow');
                }
            });
        });
    };

}(jQuery));

<script type="text/javascript">
$(function() { 
    $('.accordion').accordions()
});
</script>

Below is the HTML.

<div class="accordion">
  <div class="title">
       Title goes here
  </div>
  <div class="content">
           Content here
  </div>
</div>
1

There are 1 answers

1
Wa Kai On

For a self-written accordion the best way to achieve this is by going after these steps:

  1. on click event close all content fields
  2. get the reference to the element with $(this)
  3. open the content field you clicked

Edit: If you have the possibility, use jQuery UI with the Accordion Widget.