Pages

Friday, November 11, 2011

Going Mouseless - Implementing Keyboard Shortcuts in ASP.NET 2.0 Using Javascript


Keyboard shortcuts improve productivity by accomplishing tasks more quickly and without much effort. In applications, where the user has to select from a variety of actions to perform, keyboard shortcuts can save on time and effort. If you have used the new YahooMail or Gmail, you will be quiet familiar with these shortcuts. In this article, we will explore how to implement shortcuts and use it in our ASP.NET applications. Please note that this solution is Internet Explorer(IE) specific.
I was recently implementing a solution where users needed the ability to use shortcuts in ASP.NET applications, similar to what we see in Gmail and Yahoo mail. The requirement was as follows:
Problem Scenario
The user visits a screen which contains a series of links (linkbuttons). The user is then required to click on one of the links to navigate to a different page to perform some action (For eg: filling forms). After performing the action, the user returns back to the screen. The process is repeated by the user, quiet a number of times. Now if you visualize, the user has to use the mouse to click one of the links and then shift back to the keyboard to enter data. Then use the mouse again to go back to the main screen. What a pain, especially if someone is involved in data entry operations!!
Solution
The solution was simple. The solution was to introduce Keyboard shortcuts into the application. The user could use a shortcut instead of the mouse, to click the linkbutton and perform an action. So let us say for example, when the user clicks ‘H’, the click event of the Home button gets fired and the user navigates to the Home page.
We will see how to implement this feature in this article. It can be done easily with just a few lines of code. Follow these steps:
1.    Create an ASP.NET website. Add a master page to the application. Also create 4 pages that will be using this master page: Default.aspx, Page1.aspx, Page2.aspx and Page3.aspx. If you are unfamiliar with MasterPages, I recommend you to read my article :http://www.dotnetcurry.com/ShowArticle.aspx?ID=80
 
2.    In the default.aspx, drag and drop 3 link buttons to the form. Rename these linkbuttons as Page 1, Page 2 and Page 3 respectively.
 
The page would look like this:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">   
     <div style="width: 100%; height: 154px;">
<asp:LinkButton ID="lbPage1" runat="server" PostBackUrl="Page1.aspx">Page 1</asp:LinkButton><br />
            <br />
<asp:LinkButton ID="lbPage2" runat="server" PostBackUrl="Page2.aspx">Page 2</asp:LinkButton><br />
            <br />
<asp:LinkButton ID="lbPage3" runat="server" PostBackUrl="Page3.aspx">Page 3</asp:LinkButton><br />
            <br />
           
</div>
</asp:Content>
 
3.    In the code behind of default.aspx, add the following code to the Page_Load event
 
C#
        protected void Page_Load(object sender, EventArgs e)
        {
ClientScript.RegisterClientScriptBlock(this.GetType(), "Shortcut""document.attachEvent ('onkeyup',ShortcutKeys);",true);
        }
     
      VB.NET
     
      Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs)
ClientScript.RegisterClientScriptBlock(Me.GetType(), "Shortcut", "document.attachEvent ('onkeyup',ShortcutKeys);",True)
End Sub
 
The ClientScript.RegisterClientScriptBlock registers the client script block to the top of the rendered page using a type, key, and script literal. A client script is uniquely identified by its key and its type.
 
4.    Add a javascript file to the project called shortcut.js. Add the following code to the javascript file.
 
function ShortcutKeys()
{
        //alert(event.keyCode);
       
        // 1 Pressed For Page1
        if (event.keyCode == 49)
       {            document.getElementById('ctl00_ContentPlaceHolder1_lbPage1').click();
        }
       
        // 2 Pressed For Page2
        if (event.keyCode == 50)
        {
            document.getElementById('ctl00_ContentPlaceHolder1_lbPage2').click();
        }
       
        // 3 Pressed For Page3
        if (event.keyCode == 51)
        {                      document.getElementById('ctl00_ContentPlaceHolder1_lbPage3').click();        }      
}
The javascript, depending on the keycode, invokes the click event of the element, in our case the link button. The element is obtained by using document.getElementById(' '<%=Control.ClientID%>'').
Note: While using Master Pages, you need to refer to the control using the control's ClientID. I have directly used the ID generated.
5.    Now refer to the javascript in the MasterPage.
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript" language="javascript" src="shortcut.js"> </script>
</head>
The keyboard shortcut functionality has been added to the Default.aspx. Before we go ahead and test it, let us make the other pages too ‘mouseless’.
6.    Add the keyboard functionality in each of the pages (Page1, 2 and 3). To do so, add a button called btnHome to each of the pages. Set the PostBackUrl property of btnHome to ‘Default.aspx’.
 
7.    In the shortcut.js, add another method to handle the event for the Home button using the keyboard shortcut “H”
 
function HomeKey()
{
    if(event.keyCode == 72)
{        document.getElementById('ctl00_ContentPlaceHolder1_btnHome').click();
    }
    }
8.    Now register the newly added Client script in each of your pages as shown below :
 
C#
protected void Page_Load(object sender, EventArgs e)
      {
ClientScript.RegisterClientScriptBlock(this.GetType(), "Home""document.attachEvent('onkeyup',HomeKey);"true);
}
 
VB.NET
 
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs)
ClientScript.RegisterClientScriptBlock(Me.GetType(), "Home", "document.attachEvent ('onkeyup', HomeKey);", True)
End Sub
 
 
9.    There you are!!. Now all the pages in your application contain keyboard shortcuts.
Run Default.aspx. Test the pages by pressing 1, 2 or 3 to navigate to Page1 , Page2 or Page 3 respectively. Similarly press “H” on each of these pages to go back to the Default.aspx page.
The usage of keyboard shortcut, in this article has been kept as simple as possible. However once you understand how to use this effectively, the possibilities are endless. Gmail and Yahoomail are two good examples where keyboard shortcuts are being used to improve user interactiveness with the application.
You can download the source code of this article over here. I hope this article was useful and I thank you for viewing it. 

No comments:

Post a Comment