Home > database >  jQuery ul li trees - slideToggle only li with ul child
jQuery ul li trees - slideToggle only li with ul child

Time:12-06

I know there are a lot of similar solutions.. This one almost works :)

I have an unsorted list:

<ul id="Tree" >
  <li >First level
    <ul >
      <li><a href="pathtofile.pdf" target="_blank">File 1.1</a></li>
      <li >Second level
        <ul >
          <li><a href="pathtofile.docx" target="_blank">File 2.1</a></li>
          <li><a href="pathtofile.pdf" target="_blank">File 2.2</a></li>
          <li >Tretji nivo
            <ul >
              <li><a href="pathtofile.pdf" target="_blank">File 3.1</a></li>
              <li><a href="pathtofile.docx" target="_blank">File 3.2</a></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

And the jQuery:

$('.folder').click(function(event) {
  event.stopPropagation();
  $(this).find('>.sub-menu').slideToggle();
});

Click on .folder works as desired. The problem is that the slideToggle is triggered on all li elements. So if I click on a li > a element the file is downloaded but the ul is toggled also. I want to prevent toggle when I click on an element that has no direct ul child.

CodePudding user response:

You could add the folder class to the level text instead of the whole li tag :

$('.folder').click(function(event) {
  event.stopPropagation();
  $(this).next('.sub-menu').slideToggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="Tree" >
  <li><span >First level</span>
    <ul >
      <li><a href="pathtofile.pdf" target="_blank">File 1.1</a></li>
      <li><span >Second level</span>
        <ul >
          <li><a href="pathtofile.docx" target="_blank">File 2.1</a></li>
          <li><a href="pathtofile.pdf" target="_blank">File 2.2</a></li>
          <li><span >Tretji nivo</span>
            <ul >
              <li><a href="pathtofile.pdf" target="_blank">File 3.1</a></li>
              <li><a href="pathtofile.docx" target="_blank">File 3.2</a></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

  • Related