Search code examples
javascriptphpjstree

Jstree use HTML link with <a>


I have made a simple folder structur with jstree.

Everything works fine so far, but I was wondering whether there is a simple way to use clickable hyperlinks within the tree through "a href=". When I double click on the folder/word itself the menu structure drops down, but with a single click the hyperlink in this case google.de doesn't work. In fact nothing happens when you single click one the folders/words.

<div id="categorymenue">
 <ul>
     <li><a href="google.de">One</a>
     <ul>
     <li>Example 1</li>
     <li>Example 2
     <ul>
 <li>Example 1</li>
 <li>Expample 2</li>
 </ul></li></li></ul>
 <li>Two
     <ul>
 <li>Example 1</li>
 <li>Example 2</li>
 </ul></li>
 <li>Three
 <ul>
     <li>Example 1</li>
     <li>Example 2</li>
</ul>
</li>
<li>JOKE</li>
</ul>
</div>

enter image description here


Solution

  • <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
    </head>
    <body>
    
    
    <!-- 3 setup a container element -->
    <div id="categorymenue">
        <ul>
            <li>
                <a href="http://google.de">One</a>
                <ul>
                    <li>Example 1</li>
                    <li>Example 2
                        <ul>
                            <li>Example 1</li>
                            <li>Expample 2</li>
                        </ul>
                    </li>
                </ul>
            </li>
            <li>Two
                <ul>
                    <li>Example 1</li>
                    <li>Example 2</li>
                </ul>
        </li>
            <li>Three
                <ul>
                    <li>Example 1</li>
                    <li>Example 2</li>
                </ul>
            </li>
            <li>JOKE</li>
        </ul>
    </div>
    
    
    <script>
        $(function () {
            $('#categorymenue').jstree();
    
    
            var DELAY = 700, clicks = 0, timer = null;
            $("a").on("click", function (e) {
                clicks++;
    
                var _this = this;
                if (clicks === 1) {
    
                    timer = setTimeout(function () {
    
                        if ($(_this).attr('href')) {
                            window.location = $(_this).attr('href');
                        }
                        clicks = 0;
    
                    }, DELAY);
    
                } else {
                    clearTimeout(timer);
                    clicks = 0;
                }
    
            })
                .on("dblclick", function (e) {
                    e.preventDefault();
                });
    
        });
    </script>
    </body>
    </html>