Search code examples
jqueryhrefaccordionexpandmulti-level

jQuery accordion with href and collapsible


I'm working on an accordion menu with href link and collapsible header. The problem is, it collapse the parent when I click the the child accordion. Are there any workaround?

<ul class="accordion">
  <li>
    <a class="acc-header" href="http://www.google.com">menu - level 1</a>
    <h3>+</h3>
    <ul class="accordion">
      <li>
        <a class="acc-header" href="http://www.google.com">menu - level 2-1</a>
      <h3>+</h3>
        <ul class="accordion">menu - level 3</ul>
      </li>
      <li>menu - level 2-2</li>
    </ul>
  </li>
</ul>

<script type="text/javascript">
  $(document).ready(function(){
    $( ".accordion" ).accordion({
      header: "h3",
      collapsible: true,
      heightStyle: "content",
      active: false,
      icons: false,
      animate: 200,
    });
  });
</script>

Here is the updated version and it's working. The solution is to use the "event.stopPropagation()"(as @Renan Araújo mentioned) and remove the header setting on accordion.

https://codepen.io/CocoSkin/pen/vRQyZP


Solution

  • The according was closing because of the click event that was bubled from the anchor element.

    Use stop propagation to prevent the bubling from the anchor:

    $( ".accordion a" ).click(function(e) {
        e.stopPropagation();
    });
    

    I suggest you to read about event bubbling and check stopPropagation method.