JQtree: Associating a url with a node

1.1k Views Asked by At

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?
2

There are 2 best solutions below

1
On BEST ANSWER

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;
        }
    }
);
0
On

For posterity, I'd instead suggest doing it this way to keep the items as native links, in order to preserve the ability to open in a new tab/window, copy url, etc.

(Assuming your nodes have the url stored like in the other answer)

 $tree.tree({
     data = whatever;
     onCreateLi: function(node, $li) {
         $li.find('.jqtree-title').wrap('<a href="' + node.url + '"></a>');
     }
 });

UPDATE:

This is more than twice as fast, which is a big deal for my huge tree!

  onCreateLi: function(node, $li) {
        var a = $li.find('span')[0];
        a.outerHTML = '<a href="' + node.href + '">' + a.outerHTML + '</a>';
        }