Menus

Sunday, December 16, 2012

ASP.Net TreeView - Handle node onclick event client side using JavaScript

In this short snippet article I will describe a JavaScript code snippet to have Client Side OnClick event for ASP.Net TreeView Node. So that when we click the node of ASP.Net TreeView control we can do some client side processing too.
Need for doing this is because by default TreeView node’s do not  have any client side events hence I have made use of JavaScript to induce client side events using the JavaScript code snippet provided below
TreeView
I have a simple ASP.Net TreeView below in which I’ll display a list of Fruits.
<form id="form1" runat="server">
    <asp:TreeView ID="TreeView1" runat="server">
       <SelectedNodeStyle ForeColor="Black" />
    </asp:TreeView>
</form>
 
Now using the simple code snippet I am populating the ASP.Net TreeView with a list of fruits.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        TreeView1.Nodes.Add(new TreeNode("Mango", "Fruit1"));
        TreeView1.Nodes.Add(new TreeNode("Apple", "Fruit2"));
        TreeView1.Nodes.Add(new TreeNode("Pineapple", "Fruit3"));
        TreeView1.Nodes.Add(new TreeNode("Orange", "Fruit4"));
        TreeView1.Nodes.Add(new TreeNode("Grapes", "Fruit5"));
    }
}
 
Client Side Scripting
<script type = "text/javascript">
        function OnLoad() {
            var links = document.getElementById("<%=TreeView1.ClientID %>").getElementsByTagName("a");
            for (var i = 0; i < links.length; i++) {
                links[i].setAttribute("href", "javascript:NodeClick(\"" + links[i].id + "\", \"" + links[i].getAttribute("href") + "\")");
            }
        }
        window.onload = OnLoad;
        function NodeClick(id, attribute) {
            //Do Something
            var nodeLink = document.getElementById(id);
            alert(nodeLink.innerHTML + " clicked");
 
            //Execute the server side event.
            eval(attribute);
        }
</script>

The script is very simple. On load of the page I am fetching all the links in the nodes of the TreeView and then replacing their HREF attribute with my custom function “NodeClick” where I want to do the client side processing.
Then in the NodeClick function I am doing my client side processing and then executing the original content of the HREF which is nothing but __doPostBack call which makes a PostBack to the server.

Screenshots
ASPSnippets TreeView Selected Node Click Client Side JavaScript event

1 comment: