Search code examples
jqueryjqtree

JQtree: Associating a url with a node


I want something very simple:

A jQuery widget that presents a tree which is collapsible. I want the state saved. And I want to control what the initial state is. I want it to look very pretty. And when the user clicks on a link I want it to navigate there. Easy.

It looks to me like Jqtree is what I am looking for, but looking through all the doc I don't see the simple case of indicating the url that goes with a node in the tree.

  • Given my requirements do you agree that Jqtree is the right solution?
  • Is there a useful sample somewhere I can look to see how my case is handled?

Solution

  • The nodes are just Javascript objects so you should be able to just add another property for url. So, for example, adapting what's on the jqTree website:

    var data = [
        {
            label: 'node1',
            url: 'MyUrl.html',
            children: [
                { label: 'child1', url: 'anotherURL.html' },
                { label: 'child2', url: 'andAnotherURL.html' }
            ]
        },
        {
            label: 'node2',
            url: 'www.your.get.the.point.com',
            children: [
                { label: 'child3', url: 'google.com' }
            ]
        }
    ];
    

    Now, obviously jqTree won't do anything with this by default, so you'll have to handle that, but any time you are able to get a node, you should be able to retrieve it's .url:

    var theURL = myNode.url;
    

    So, for example, it looks like jqTree has a tree.click event:

    $('#tree1').bind(
        'tree.click',
        function(event) {
            // The clicked node is 'event.node'
            var node = event.node;
            var theURL = node.url;
            if (theURL) {
                location.href = theURL;
            }
        }
    );