Sunday, February 22, 2009

Displaying a hidden panel on button click using client side code

Sometimes there is part of the web page we want to display only after the user clicked a button. For example, we are displaying a list of customer, and when the user clicks a button that says "Add New Customer", a panel is displayed with controls to create the new customer.
It is very simple to implement using ASP.NET with server-side code. The panel is created with Visible=False, and the button has an event handler that all it does is setting the visibility of the panel to true:
protected void Button1_OnClick(object sender, EventArgs e)
{
Panel1.Visible = true;
}

However, choosing this implementation means that there will be a full postback with every button click, and the user will have to wait for reload of the web page, when actually nothing is needed from the server.

To implement this code on the client using javascript, I needed a client-side button, instead of the Button control that forces postback when clicking it. I used the HTML button:
<input id="Add Customer" type="button" value="Add Customer" />

Now I had to add the code to display the hidden panel when the button is clicked. First I tried what seemed most logical, the javascript equivalent of the Visible ASP.NET's property.
So now the button definition in the aspx page looked like that:
<input id="Add Customer" type="button" value="Add Customer" onclick="document.getElementById('Panel1').style.visibility='visible'"/>

When I tried to run the code, I got an error saying that the search for "Panel1" did not get any valid object.
It turned out that when I set the Visible property of the panel to "false", the control wasn't created at all at the resulting html page, so the javascript cannot access it.
So I changed the Visible property to "true", and added a javascript right after its definition, setting its visibility to "hidden":
...
</asp:Panel>
<script type="text/javascript">
document.getElementById('Panel1').style.visibility='hidden';
</script>

Now it worked... almost. The html page did not display the panel until I clicked the button, but it left a blank place where it was supposed to be. That is not how I wanted it, and not as it worked before with the server-side implementation: I didn't want this blank space on the page when the panel is not displayed.
So I played a little with the style properties of javascript, and found out that the "display" property did just what I wanted.
So this is how the button definition looks now:

<input id="Add Customer" type="button" value="Add Customer"
onclick="document.getElementById('Panel1').style.display=''"/>

And the javascript right after the definition of the panel:

<script type="text/javascript">
document.getElementById('Panel1').style.display='none';
</script>

Now when I click the button, the panel for creating a new customer is displayed right away, without waiting for the page to load again.

No comments:

Post a Comment