0

THE PROBLEM: I am building a nested tree using a light package called "listree", but encountering an error whenever I place a link into a parent element in the list.

THE ERROR When clicking the link, a click event is triggered to expand the tree (because the link is contained within a div requiring this event listener) and breaking the flow to link redirection.

THE QUESTION How can I inhibit the firing of this event trigger when clicking a link in a parent that has a click EventListener.

https://codepen.io/atopbio/pen/zYwROwV/

<div class="listree-submenu-heading">Settings<a href="https://www.google.com"> A link not working</a></div>

1 Answers1

0

You can use event.stopPropagation() and then add an id to the link and event listener to trigger when the link is clicked.

See snippet below:

<html>
  <head>
    <link rel="stylesheet" href="https://unpkg.com/listree/dist/listree.min.css"/>
    <title>LisTree</title>
  </head>
  <body>
    <ul class="listree">
        <li>

            <div class="listree-submenu-heading">Settings<a id="my-link" href="https://www.google.com"> A link not working</a></div>
            <ul class="listree-submenu-items">
                <li>
                    <div class="listree-submenu-heading">Personal Settings</div>
                    <ul class="listree-submenu-items">
                        <li><a href="">Password Settings</a></li>
                        <li><a href="">Viewing Preferences</a></li>
                    </ul>
                </li>
                <li>
                    <div class="listree-submenu-heading">Org Settings</div>
                    <ul class="listree-submenu-items">
                        <li><a href="">Teams</a></li>
                        <li><a href="">Billing</a></li>
                    </ul>
                </li>
            </ul>
        </li>
    </ul>
    <script src="https://unpkg.com/listree/dist/listree.umd.min.js"></script>
    <script>
        listree();
        //add handler function
      function handler(event) {
        // stops parent events from being triggered
        event.stopPropagation();       
      }
      //add listner for click
      document.getElementById("my-link").addEventListener('click', handler, false);
    </script>
  </body>
</html>

Also check out this answer here

RyDog
  • 1,169
  • 1
  • 9
  • 12