jsTree - Get the selected node on loaded.jstree event

12,071

Seems according to the documentation of the demo here :

http://www.jstree.com/demo

you can do :

.one("reselect.jstree", function (event, data) { });

or

.bind("select_node.jstree", function (event, data) {  
                // `data.rslt.obj` is the jquery extended node that was clicked 
                alert(data.rslt.obj.attr("id")); 
            })

Read carefully the documentation as :

one is used, this is because if refresh is called those events are triggered

// 1) if using the UI plugin bind to select_node
        .bind("select_node.jstree", function (event, data) { 
            // `data.rslt.obj` is the jquery extended node that was clicked
            alert(data.rslt.obj.attr("id"));
        })
        // 2) if not using the UI plugin - the Anchor tags work as expected
        //    so if the anchor has a HREF attirbute - the page will be changed
        //    you can actually prevent the default, etc (normal jquery usage)
        .delegate("a", "click", function (event, data) { event.preventDefault(); })

For the last event delegate, instead of writing event.preventDefault();, you can make your redirection correctly if you're not using the UI plugin, and write : window.location = $(this).attr('href');

Share:
12,071
Yair Nevet
Author by

Yair Nevet

Lead Software Engineer. Has a wealth experience in software architecture and development. Obsessed technology books reader and enjoys from well-done tech blogs. Happy to share from my knowledge and to learn from others knowledge! See more about me: My GitHub account My LinkedIn profile Tip: Don't be too reckless with the Bounty feature of stackoverflow! This is part of my favorite tech stack: .NET / C# ORM Databases: SQL / NoSql XML / XSD JavaScript jQuery angularJS HTML CSS

Updated on June 04, 2022

Comments

  • Yair Nevet
    Yair Nevet almost 2 years

    How can I get the selected node on the loaded.jstree event?

    what should I do in the event handler:

        $('#Tree').bind('loaded.jstree', function(event, data){//TODO: How to get the selected node here?}).jstree();
    

    By the way, I found out that the event data arg object contains a function called get_selected() but couldn't get anything from it.

    My purpose is to redirect the client to the current selected node (by 'url' attribute).

    Thanks in advance