Introduction
igTree simplifies the presentation of your hierarchical data into a web-based tree structure, depicting familiar parent-child relationships between nodes of information. This blog post demonstrates how to achieve custom implementation of a context menu for the igTree. Our goal is to make a context menu that appears upon user interaction with the igTree. The context menu offers choices related to the selected node – new sibling node, new child node, edit node and delete node. The screenshot bellow demonstrates the final result.
Before you start
Before you start you must satisfy the prerequisites for working with NetAdvantage for jQuery and in particular with the Infragistics jQuery Tree:
Requirements:
· jQuery library (version 1.4.4 or newer)
· jQuery UI (version 1.8.1 or newer)
· NetAdvantage for jQuery 2012 Vol.2
- // Initialize Infragistics loader
- $.ig.loader({
- scriptPath: "http://localhost/ig_ui/js/",
- cssPath: "http://localhost/ig_ui/css/",
- resources: "igTree,igDialog,igEditors,igValidator"
- });
Create an igTree with a Context Menu
To create an igTree with a context menu, you need to accomplish the following steps:
· Initialize the igTree
· Databind the igTree to a data source
· Implement a custom context menu for the igTree
Initialize the igTree
Before initializing the igTree you must initialize the Infragistics loader. Paths to the JavaScript and CSS files are set to point to localhost. In order to load resources for the igTree, you need to set the resources option to the string “igTree”, after that pass a function to the Infragistics loader which initializes an instance of the igTree in an HTML DIV.
- <script type="text/javascript">
- // Initialize Infragistics loader
- $.ig.loader({
- scriptPath: "http://localhost/ig_ui/js/",
- cssPath: "http://localhost/ig_ui/css/",
- resources: "igTree"
- });
- $.ig.loader(function () {
- // Initialize igTree
- $("#tree").igTree({
- ...
- });
- });
- script>
In HTML:
- <div id="tree"><div>
Databind the igTree to a data source
The data source which is going to be used for data binding is a JSON object. The JSON object represents a simple table of contents from the Infragistics Help.
- // JSON object represent Table of Content from the Infragistics Help
- var toc = [{
- Text: "NetAdvantage jQuery 2012.2",
- Nodes: [{
- Text: "NetAdvantage for jQuery Overview"
- }, {
- Text: "What's New",
- Nodes: [{
- Text: "What's New in 2012 Volume 2"
- }, {
- Text: "What's New Revision History"
- }, {
- Text: "Touch Support for NetAdvantage for jQuery Controls"
- }]
- }, {
- Text: "Deployment Guide",
- Nodes: [{
- Text: "Using JavaScript Resouces in NetAdvantage for jQuery"
- }, {
- Text: "JavaScript Files in NetAdvantage for jQuery"
- }, {
- Text: "Styling and Theming NetAdvantage for jQuery"
- }, {
- Text: "Infragistics Content Delivery Network (CDN) for NetAdvantage for jQuery"
- }]
- }]
- }];
To successfully databind the igTree, you have to set the dataSourceType option to “json”, the dataSource to the toc variable and set the bindings options - textKey to toc’s property Text and childDataProperty to toc’s property Nodes.
- // Initialize igTree
- $("#tree").igTree({
- dataSourceType: "json",
- dataSource: toc,
- bindings: {
- textKey: "Text",
- childDataProperty: "Nodes"
- }
- });
The following screenshot demonstrate the result of these steps.
Implement a custom context menu for the igTree
The custom context menu is going to offer commands for creating new sibling nodes, new child nodes, editing nodes and deleting nodes.
For each command an HTML DIV element is created with class name being the corresponding command (this is used later to handle commands in JavaScript).
- <div class="context-menu">
- <div class="new-node"><span>New Sibling Nodespan>div>
- <div class="new-child-node"><span>New Child Nodespan>div>
- <div class="edit-node"><span>Edit Nodespan>div>
- <div class="delete-node"><span>Delete Nodespan>div>
- div>
And the DIVs are wrapped in another DIV with a context-menu class applied. These elements are styled with the following CSS:
- <style type="text/css">
- .context-menu
- {
- border:1px solid #aaa;
- position:absolute;
- background:#fff;
- display:none;
- font-size:0.75em;
- }
- .context-menu span
- {
- width:100px;
- display:block;
- padding:5px 10px;
- cursor:pointer;
- }
- .context-menu span:hover
- {
- background:#3BB7EB;
- color:#fff;
- }
- style>
The final step is to handle the right click of a tree node. In order to do that, you have to handle the contextmenu event when right click is fired on the node anchor. You have to prevent the default behavior of the browser (which is to open the default browser context menu). To get a reference to the tree node element, you would use the igTree API. Get the closest node from igTree through the method nodeFromElement and store it. Later, this node is going to help us with the command functionality.
It is time to build the context menu and shown it to the end-user. Grab the DIV with context-menu class via jQuery and store it in a variable. Then create overlay HTML div and append it to the body.
Note:The context menu has to have a zIndex greater than the zIndex of the overlay.
You would hide the element by subscribing to the click event of the overlay DIV.
- // Context menu
- var node = "";
- $("body").delegate("li[data-role=node] > a", "contextmenu", function (evt) {
- evt.preventDefault();
- node = $('#tree').igTree('nodeFromElement',
- $(evt.target).closest('li[data-role=node]'));
- var cmenu = $(".context-menu");
- $(" ").
- css({
- left: "0px",
- top: "0px",
- position: "absolute",
- width: "100%",
- height: "100%",
- zIndex: "100"
- }).
- click(function() {
- $(this).remove();
- cmenu.hide();
- }).
- appendTo(document.body);
- cmenu.
- css({
- left: evt.pageX,
- top: evt.pageY,
- zIndex: "101"
- }).
- show();
- return false;
- });
And the result after right-clicking on the “What’s New in 2012 Volume 2” node from the igTree is illustrated in the following screenshot:
Add Functionality to the context menu commands
The context menu is now built. Next step is to implement the following commands – adding a new sibling node, adding a new child node, editing a node and deleting a node. In order to create the best end-user experience we also use other Infragistics components such as igDialog, igEditors, igButton, and igValidators.
Note: To load them in the project you need to add them in Infragistics loader option resources. Infragistics Button requires the igShared resource, but in our case it is not necessary to load, because it already loaded by the igTree.
- // Initialize Infragistics loader
- $.ig.loader({
- scriptPath: "http://localhost/ig_ui/js/",
- cssPath: "http://localhost/ig_ui/css/",
- resources: "igTree,igDialog,igEditors,igValidator"
- });
The click event is handled for each command in the context menu as follows:
- // Add child node
- $("body").delegate(".context-menu .new-child-node", "click", function (evt) {
- if ($(this).children().size() == 1 && node != "") {
- // Add command functionality here
- }
- });
Adding a New Sibling node
An HTML DIV element is created on the fly for the dialog window with an HTML INPUT and a BUTTON to save the new value from the input.
- // Adding a new sibling node
- $("body").delegate(".context-menu .new-node", "click", function(evt) {
- if( $(this).children().size() == 1 && node != "") {
- // Add command functionality here
- $(' ').
- appendTo("body");
- }
- });
The dialog window is initialized with a custom header text, custom image icon in the header and an event handler for the stateChanging event (if the action is close, dialog is destroyed and removed from DOM).
- // Initialize igDialog
- $("#dialog").igDialog({
- headerText: "Save new node",
- imageClass: "ui-icon ui-icon-info",
- width: "340px",
- height: "110px",
- stateChanging: function (evt, ui) {
- // Check the igDialog state
- if (ui.action === "close") {
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- }
- });
The editor is initialized with null text and required. The input is checked onblur and onchange whether it is valid.
- // Initialize igEditor
- $("#newValue").igEditor({
- nullText: "Enter new value",
- required: true,
- validatorOptions: {
- onblur: true,
- onchange: true,
- onsubmit: true,
- animationHide: 0
- }
- });
- $("#newValue").focus();
The button is initialized with the label text being “Save” and a click event handler is added. In the event handler we check whether the input is valid and if it is, a new sibling node is added via the addNode method of the igTree.
Note: To determine the parent node of a clicked node, you have to use the parentNode method of the igTree and pass the jQuery element of the clicked node.
After that the dialog is destroyed and removed from DOM.
- // Initialize igButton
- $("#btnSave").igButton({
- labelText: "Save",
- click: function () {
- if ($("#newValue").igEditor("validate")) {
- $("#tree").igTree("addNode", {
- Text: $("#newValue").val()
- },
- $("#tree").igTree("parentNode", node.element)
- );
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- }
- });
The following code handles keyboard input while the editor is on focus. So, upon pressing the enter button, click is simulated on the save button.
- // Submit on enter
- $("#newValue").keyup(function (event) {
- if (event.keyCode == 13) {
- $("#btnSave").click();
- }
- });
Upon pressing of the escape button, the dialog is closed, destroyed and removed from DOM.
- // Close igDialog and destroy on ESC
- $("#newValue").keyup(function (event) {
- if (event.keyCode == 27) {
- $("#dialog").igDialog("close");
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- });
Finally, the context menu and overlay are hidden through this code:
- $(".context-menu").hide();
- $(".overlay").hide();
That is how you actually add the new sibling node:
- // Add new sibling node
- $("body").delegate(".context-menu .new-node", "click", function(evt) {
- if( $(this).children().size() == 1 && node != "") {
- $(' ').
- appendTo("body");
- // Initialize igDialog
- $("#dialog").igDialog({
- headerText: "Save sibling node",
- imageClass: "ui-icon ui-icon-info",
- width: "340px",
- height: "110px",
- stateChanging: function (evt, ui) {
- // Check the igDialog state
- if (ui.action === "close") {
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- }
- });
- // Initialize igEditor
- $("#newValue").igEditor({
- nullText: "Enter new value",
- required: true,
- validatorOptions: {
- onblur: true,
- onchange: true,
- animationHide: 0
- }
- });
- $("#newValue").focus();
- // Initialize igButton
- $("#btnSave").igButton({
- labelText: "Save",
- click: function () {
- if ($("#newValue").igEditor("validate")) {
- $("#tree").igTree("addNode", {
- Text: $("#newValue").val()
- },
- $("#tree").igTree("parentNode", node.element)
- );
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- }
- });
- // Submit on enter
- $("#newValue").keyup(function(event) {
- if(event.keyCode == 13){
- $("#btnSave").click();
- }
- });
- // Close igDialog and destroy on ESC
- $("#newValue").keyup(function(event) {
- if(event.keyCode == 27){
- $("#dialog").igDialog("close");
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- });
- $(".context-menu").hide();
- $(".overlay").hide();
- }
- });
And the result:
Adding a New Child Node
The way a new child node is implemented is the same. The only difference is that you do not need to take the parent node of the node that has been click as in the previous command implementation. Just point to the jQuery element of the clicked node:
- $("#tree").igTree("addNode", {
- Text: $("#newValue").val()
- },
- node.element
- );
The following is the implementation for the new child node:
- // Add child node
- $("body").delegate(".context-menu .new-child-node", "click", function(evt) {
- if( $(this).children().size() == 1 && node != "") {
- $(' ').
- appendTo("body");
- // Initialize igDialog
- $("#dialog").igDialog({
- headerText: "Save child node",
- imageClass: "ui-icon ui-icon-info",
- width: "340px",
- height: "110px",
- stateChanging: function (evt, ui) {
- // Check the igDialog state
- if (ui.action === "close") {
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- }
- });
- // Initialize igEditor
- $("#newValue").igEditor({
- nullText: "Enter new value",
- required: true,
- validatorOptions: {
- onblur: true,
- onchange: true,
- animationHide: 0
- }
- });
- $("#newValue").focus();
- // Initialize igButton
- $("#btnSave").igButton({
- labelText: "Save",
- click: function () {
- if ($("#newValue").igEditor("validate")) {
- $("#tree").igTree("addNode", {
- Text: $("#newValue").val()
- },
- node.element
- );
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- }
- });
- // Submit on enter
- $("#newValue").keyup(function(event) {
- if(event.keyCode == 13){
- $("#btnSave").click();
- }
- });
- // Close igDialog and destroy on ESC
- $("#newValue").keyup(function(event) {
- if(event.keyCode == 27){
- $("#dialog").igDialog("close");
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- });
- $(".context-menu").hide();
- $(".overlay").hide();
- }
- });
And the result:
Edit Node
The way node editing is implemented is identical. The only difference is that you need to update the node with the new value from the input.
- $(node.element).
- find("a:first").
- text($("#newValue").
- val()
- );
Note:Text is changed only in the HTML on the client side.
The following is the implementation for the edit node:
- // Edit node
- $("body").delegate(".context-menu .edit-node", "click", function(evt) {
- if( $(this).children().size() == 1 && node != "") {
- // Note: Text is changed only on client side.
- // To change on the server side, you have to update data source.
- $(' ').
- appendTo("body");
- // Initialize igDialog
- $("#dialog").igDialog({
- headerText: "Edit node text",
- imageClass: "ui-icon ui-icon-info",
- width: "330px",
- height: "110px",
- stateChanging: function (evt, ui) {
- // Check the igDialog state
- if (ui.action === "close") {
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- }
- });
- // Initialize igEditor
- $("#newValue").igEditor({
- value: node.element.children('a').text(),
- required: true,
- validatorOptions: {
- onblur: true,
- onchange: true,
- onsubmit: true,
- animationHide: 0
- }
- });
- $("#newValue").focus();
- // Initialize igButton
- $("#btnEdit").igButton({
- labelText: "Edit",
- click: function () {
- if ($("#newValue").igEditor("validate")) {
- $(node.element).
- find("a:first").
- text($("#newValue").
- val()
- );
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- }
- });
- // Submit on enter
- $("#newValue").keyup(function(event) {
- if(event.keyCode == 13) {
- $("#btnEdit").click();
- }
- });
- // Close igDialog and destroy on ESC
- $("#newValue").keyup(function(event) {
- if(event.keyCode == 27){
- $("#dialog").igDialog("close");
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- });
- $(".context-menu").hide();
- $(".overlay").hide();
- }
- });
And the result:
Delete Node
Upon deleting a run-time confirmation dialog is created and a node is created to confirm deleting of the clicked node.
- $('
- appendTo("body");
- $("#message").html("Are you sure to delete " + node.element.children('a').text() + " permanently?");
The dialog window is implemented similarly to the previous commands.
- // Initialize igDialog
- $("#dialog").igDialog({
- headerText: "Delete node",
- imageClass: "ui-icon ui-icon-trash",
- width: "620px",
- height: "150px",
- stateChanging: function (evt, ui) {
- // Check the igDialog state
- if (ui.action === "close") {
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- }
- });
The button’s click event gets the node path of the clicked node and calls the removeAt method of the igTree to delete a node from the tree. After that the dialog is closed, destroyed and removed from the DOM.
Here is the code for deleting a node:
- // Delete node
- $("body").delegate(".context-menu .delete-node", "click", function(evt) {
- if( $(this).children().size() == 1 && node != "") {
- $('
- appendTo("body");
- $("#message").html("Are you sure to delete " + node.element.children('a').text() + " permanently?");
- // Initialize igDialog
- $("#dialog").igDialog({
- headerText: "Delete node",
- imageClass: "ui-icon ui-icon-trash",
- width: "620px",
- height: "150px",
- stateChanging: function (evt, ui) {
- // Check the igDialog state
- if (ui.action === "close") {
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- }
- });
- // Initialize igButton
- $("#btnOk").igButton({
- labelText: "OK",
- click: function () {
- $("#tree").igTree("removeAt", node.path);
- $("#dialog").igDialog("close");
- $("#dialog").igDialog("destroy");
- $("#dialog").remove();
- }
- });
- // Submit on enter
- $(document).keyup(function(event) {
- if(event.keyCode == 13){
- $("#btnOk").click();
- }
- });
- $(".context-menu").hide();
- $(".overlay").hide();
- }
- });
And the result:
The sample is going to be available after 12.2 is officially released.