JavaScript Page 3 - Adding Elements to a Tree with TreeView jQuery |
As I stated right at the beginning of this article, the "TreeView" plug-in comes equipped with an option that allows you to easily add elements to an existing tree in a truly dynamic way. The option in question is called, not surprisingly, "add," and it's very simple to use. So let's get right to it with a functional code sample. Below I coded for you a brand new example that shows how to use this option to append a single sub link to a sample tree. Check it out:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Example on jQuery TreeView (using the add option)</title> <link rel="stylesheet" href="jquery.treeview.css" type="text/css" /> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.treeview.js"></script> <script> // build treeview after web page has been loaded $(document).ready(function(){ var tree = $("#menu").treeview(); $("#link").click(function(){ var subLink = $("<li>New Sub link<ul><li>Sub link 1</li></ul></li>").appendTo(tree); tree.treeview({ add: subLink }); }); }); </script> </head> <body> <p><a href="#" id="link">Add Sub link</a></p> <ul id="menu"> <li>Link 1 <ul> <li>Sub link 1</li> <li>Sub link 2</li> <li>Sub link 3</li> <li>Sub link 4</li> <li>Sub link 5</li> </ul> </li> <li>Link 2 <ul> <li>Sub link 1</li> <li>Sub link 2</li> <li>Sub link 3</li> <li>Sub link 4</li> <li>Sub link 5</li> </ul> </li> <li>Link 3 <ul> <li>Sub link 1</li> <li>Sub link 2</li> <li>Sub link 3</li> <li>Sub link 4</li> <li>Sub link 5</li> </ul> </li> <li>Link 4 <ul> <li>Sub link 1</li> <li>Sub link 2</li> <li>Sub link 3</li> <li>Sub link 4</li> <li>Sub link 5</li> </ul> </li> <li>Link 5 <ul> <li>Sub link 1</li> <li>Sub link 2</li> <li>Sub link 3</li> <li>Sub link 4</li> <li>Sub link 5</li> </ul> </li> </ul> </body> </html>
As you may have noticed, in the above example there's a simple hyperlink that allows you to add a new element to the existing tree. In this case, each time someone clicks on the link, it invokes the aforementioned "add" option, and in consequence, a new sub link will be appended to the targeted tree. To help you understand more clearly how this process works, below I included a screen shot that shows how single sub links are added to the previous tree. Have a look at it:
See how easy it is to dynamically append elements to a tree via the "add" option? I guess you do. Though, in case you still have some doubts with reference to this procedure, in the final section of this tutorial I'm going to code a similar example that will show you how to add multiple sub links. To see how this last example will be created, click on the link that appears below and read the upcoming segment.
blog comments powered by Disqus |
|
|
|
|
|
|
|