Search code examples
jqueryjquery-ui-accordion

jQuery accordion click trigger on specific element


I have a problem with a simple jQuery accordion script. I'm using it on this page to list a few events: http://www.melisayavas.com/kush-project/

The problem I'm having is that the script collapses when the user clicks anywhere inside the wrapper. I need the script to collapse only when the user clicks on the title of the event.

You can see this jsfiddle that has the same problem: http://jsfiddle.net/mcDeE/

The full code of the script I'm using can be found here: http://pastebin.com/hJEufLQU

This is the HTML:

<div id="va-accordion" class="va-container" style="">
    <div class="va-wrapper">
        <div class="va-slice" style="opacity: 1;">
            <div class="va-title" style="">
                <h2>Relationship, 26 February 2013</h2>
            </div>
            <div class="va-content" style="display: block;">
                <div class="event-left"></div>
                <div class="event-right"></div>
            </div>
        </div>
        <div class="va-slice" style="opacity: 0.2;">
        <div class="va-slice" style="opacity: 0.2;">
    </div>
</div>

Solution

  • The problem I'm having is that the script collapses when the user clicks anywhere inside the wrapper. I need the script to collapse only when the user clicks on the title of the event.

    In order to get your desired result you have to block the event propagation before it reaches the accordion root element. You only need to do this when the click occurs on the .va-content element.

    $(function() {
        $('#va-accordion').vaccordion();
        $(".va-content").click(function(e) {
            e.stopPropagation();                    
        });
    });
    

    Why this work?

    Events propogate starting from the root element till the target element (capture phase) and after reaching the target, they climb up back to the root element (bubbling phase). The target element is the element that received the event.

    It's possible to register event listeners both on the capture phase, both on the bubbling phase. Here, we're using jQuery that registers the event on the bubbling phase.

    stopPropagation permits to block the event propagation through the DOM.

    That's an article I wrote, in case you need more info about W3C event model.