Learning CakePHP

May 27, 2011

JSTree – onclick event on link nodes not firing.

Filed under: Ajax, jquery, jstree — ldazo @ 6:14 am

[Note:  not really a cakephp issue ]

I am using jstree to represent my data like a directory listing. So far, jstree gave me the functionality i needed, till one of my teammate pointed to me that clicking a node in the tree does not fire up the onclick event i assigned to that node.

The json_data each node is as follows:

{"data":{"title":"1st Commentary","attr":{"id":"article-85", "class":"articles","onclick":"summary(event)"}} 

and the html output of the node is like this:

<div id="articles">
    <ul>
        <li>
            <ins>&nbsp;</ins>
            <a href="#" onclick="summary(event)"  id=article-85">
            <ins>&nbsp;</ins>1st Commentary</a>
        </li>
    </ul>
</div>

I have a function defined as:

function summary(event) {...}

and its not firing in Google Chrome, though it works perfectly okay with Mozilla Firefox.

The odd thing is that if i copy the whole ‘html output’ in a separate page, the onclick event works fine in Chrome. So i figured it might be a jstree issue. There must be a right way of delegating this event to a handler rather than specifying it to the list of attributes of each node. And after googling i found out that, yes there is. Thanks to a lot of people who continuously responds to questions in stackoverflow. Here is the thread [http://stackoverflow.com/questions/4611317/how-can-i-make-jstree-render-nodes-as-links]

so the solution to my problem is this:

 $('#articles')
        .jstree(...)
        .delegate('a', 'click', summary);

Blog at WordPress.com.