1

I am using JQuery to load content into a div element and everything is working ok.

$("#content").load('www.urltogetcontentfor.com')

I now want to extend this. The structure I have is that of a tree where each branch may (or may not) have child branches attached to it. What I want to happen is that the JQuery load command is recursively called until there are no children attached to it. Something like the following steps:

  1. call Jquery load function to load content into 'content' div.
  2. if the load function returns that children are attached
  3. Call JQuery load function again to get children
  4. repeat steps 2 and 3 until no children are available.

Has anyone done this in JQuery or know of a plug in which handles this?

Thanks

1 Answer 1

3

Loading content recursively could be done with this principle:

function loadTree($element) {
  $element.each(function(){
    this.load('url', function(){
      loadTree(this.find('.children'));
    });
  });
}

loadTree($('#content'));

You call the function with a jQuery object. It loops through the elements in the object and calls load for each. In the success callback it picks the children in the loaded code and calls itself.

However, if possible you should try to get the entire tree using one request, for example returning the data as JSON and create elements from that.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for the last comment more than the code, this is a much better and faster experience for the user.
@Guffa. I have got it set up at the moment to return the whole list as one call but depending on how many levels the tree goes down the load can take quite a while to load. This is why I thought about splitting it to individual calls, that way there will at least be some information on screen while the rest loads in.
@John: You could make a combination and load only the first levels from start, then to reduce the number of requests you could load a node with all it's children instead of loading each node separately. Do you need to load the entire tree from start, or could you leave nodes unexpanded and load them when the user expands them?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.