0
votes

I have an accordion for a site that within the button that activates the accordion content there resides a span tag with an icon. Normally I would use simple CSS to add the icon but this is a unique site where I can't use standard techniques due to the way it has to be embedded.

So instead I have had to add a span tag and I have built the accordion that for the most part works. It expands and collapses just fine if you click anywhere on the title panel link.

The issue I am having is if you click the span icon area. It always expands the content area and never collapses it. So for example if the content area is expanded and I click the icon to collapse it the content collapses but then expands again.

I have a JSFiddle showing where I am and the issue I am having.

HTML

<div class="accordion">
<div class="accordion-section">
    <a class="accordion-section-title" href="#accordion-1">Panel 1 <span class="has-icon">icon</span></a>
    <div id="accordion-1" class="accordion-section-content">
        <p>Content displayed for the <b>first</b> accordion panel.</p>
    </div>
</div>
<div class="accordion-section">
    <a class="accordion-section-title" href="#accordion-2">Panel 2 <span class="has-icon">Icon</span></a>
    <div id="accordion-2" class="accordion-section-content">
        <p>Content displayed for the <b>second</b> accordion panel.</p>
    </div>
</div>
<div class="accordion-section">
    <a class="accordion-section-title" href="#accordion-3">Panel 3 <span class="has-icon">Icon</span></a>
    <div id="accordion-3" class="accordion-section-content">
        <p>Content displayed for the <b>third</b> accordion panel.</p>
    </div>
</div>

jQuery

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();
 });

CSS

a.accordion-section-title {
    display: block;
    margin: 0;
    padding: 10px 15px;
    border: 1px solid #CCC;
    background-color: #AAA;
}
a.accordion-section-title:hover {
    background-color: #CCC;
}
a.accordion-section-title span {
    position: absolute;
    right: 20px;
}
.accordion-section-content {
    display: none;
    margin: 0;
    padding: 5px 15px;
    background-color: #EEE;
}
1

1 Answers

1
votes

$(e.target) when clicking on the span is not "active". If you change

if($(e.target).is('.active')) { to if($(e.target).closest('a').is('.active')) {

the accordion works as expected. fiddle.