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

Posted by: Suprotim Agarwal , on 12/19/2007, in Category ASP.NET
Views: 200001
Abstract: 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.
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 : https://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 Object, ByVal 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 Object, ByVal 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. 

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by amal on Thursday, December 27, 2007 2:27 AM
Nice article
Comment posted by sushma on Wednesday, January 9, 2008 6:06 AM
I want example in Asp.net(vb) take one letter ex: a/b/ keys
Comment posted by Herman mandari on Thursday, January 10, 2008 7:15 PM
Hallow hii
I am trying your code for creating access key, but when I browse and hit the numbers, or H does not work! what is wrong please, help me deadline is next week for my assignment
Comment posted by Suprotim Agarwal on Friday, January 11, 2008 9:11 AM
Sushma: The article is in both C# and VB.NET
Herman: Did you download the sample project and try it out on that. Just use alert(event.keyCode) to detect the keypress and then write code to handle that keyCode as demoed in the javascript file
Comment posted by Bill Beckelman on Tuesday, January 22, 2008 5:08 PM
This will only work in IE. Browsers such as FireFox and Safari use addEventListner instead of attachEvent and the event names don't use "on"

http://developer.mozilla.org/en/docs/DOM:element.addEventListener

I messed with your code some and managed to get FireFox to call the keyup event but had trouble from there.

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim str As String = "if (document.addEventListener){" & vbCrLf & "document.addEventListener('keyup', ShortcutKeys,true);" & vbCrLf & _
            "} else if (document.attachEvent){" & vbCrLf & _
            "document.attachEvent('onkeyup', ShortcutKeys);" & vbCrLf & "}"

        ClientScript.RegisterClientScriptBlock(Me.GetType(), "Shortcut", str, True)

    End Sub



function ShortcutKeys(e)
{
        //alert(event.keyCode);
        
           // Internet Explorer doesn't pass the event as a parameter
       
       if(!e)
          e=window.event;
        
        // No. 1 Pressed For Page1
        if (e.keyCode == 49)
        {
            document.getElementById('ctl00_ContentPlaceHolder1_lbPage1').click();
        }
        
        // No. 2 Pressed For Page2
        if (e.keyCode == 50)
        {
            document.getElementById('ctl00_ContentPlaceHolder1_lbPage2').click();
        }
        
        // No. 3 Pressed For Page3
        if (e.keyCode == 51)
        {            
            document.getElementById('ctl00_ContentPlaceHolder1_lbPage3').click();
        }      
}

function HomeKey(e)
{
    if(e.keyCode == 72)
    {
        document.getElementById('ctl00_ContentPlaceHolder1_btnHome').click();
    }
}

Get the following error:
document.getElementById("ctl00_ContentPlaceHolder1_lbPage1").click is not a function
[Break on this error] document.getElementById('ctl00_ContentPlaceHolder1_lbPage1').click()...

Maybe someone can take this further?

Thanks for your work.

Bill
http://beckelman.net
Comment posted by rudgr on Wednesday, January 23, 2008 2:49 AM
Would it be possible to detect key combinations as well?
Comment posted by Suprotim Agarwal on Wednesday, January 23, 2008 5:43 AM
thanks bill for pointing that out. I have now mentioned IE in the article. I will try out a mozilla solution sometime later.
Comment posted by Wesley bakker on Wednesday, January 23, 2008 3:55 PM
What's wrong with the good old xhtml attribute 'accesskey'? Works on ALL browsers without javascript.
Comment posted by Subramannian on Thursday, January 24, 2008 12:21 AM
nice articles
Comment posted by criztoo on Monday, January 28, 2008 2:52 AM
Please try out the mozilla solution and post......... Don't avoid mozilla.
Comment posted by Suprotim Agarwal on Tuesday, January 29, 2008 12:29 PM
Hi criztoo..yes Mozilla cannot be avoided :) I have the mozilla solution on my agenda. Will work on it as soon as possible. Thanks for your comments.
Comment posted by vishal on Friday, February 15, 2008 8:08 AM
document.getElementById(' '<%=Control.ClientID%>''). it is not working when i use master page so can any one tell me how to access control on default page through javascript in master page.
Comment posted by Akhilesh Soni on Wednesday, March 19, 2008 8:18 AM
I can not under that why we use ct100 before ct100_ContentPlaceHolder1_page1 in js file.
Comment posted by vijay on Tuesday, September 30, 2008 4:34 AM
shortcut keys
Comment posted by Sandeepan Kundu on Sunday, December 7, 2008 12:59 PM
The code is simple but does not applies to multiple browsers...
I am trying to make all the function keys work in my web application.
for example F1 default help but it should be overridden also like F5 has to overridden with custiom behaviour...
can anybody provide supportive information for the same....
Comment posted by Sriram on Saturday, March 7, 2009 10:01 PM
Thats great work. But you could use the Access Key attribute on the controls to do the same. It would now mean a Key Combination Alt+<AccessKey>.
Comment posted by amit on Tuesday, June 9, 2009 4:23 AM
Please help!!! I m getting dis error "Failed to map the path '/website1App_Code'."
Comment posted by Suprotim Agarwal on Wednesday, June 10, 2009 3:57 AM
Where do you get the error?
Try using Server.MapPath(("~/YourPath");)
Comment posted by Dia Awad on Tuesday, June 16, 2009 5:06 AM
I think there is an error in the KeyCode provided for 1,2,3.
These codes are for onKeyPress event and not the onKeyUp event.
If you replace them with 97,98,99 in the js file every thing will work well. Great article.
Comment posted by Peeter on Tuesday, September 1, 2009 6:15 AM
how to select a particular row using keys [alt+u].(Select as in select,edit and delete). if i press the key then the value of the row should get selected
Comment posted by Peeter on Tuesday, September 1, 2009 10:05 AM
Please reply fast its urgent
Comment posted by Gopal Yadav on Tuesday, August 30, 2011 6:07 AM
I can not under that why we use ct100 before ct100_ContentPlaceHolder1_page1 in js file.
Comment posted by AMIT VARMA on Friday, June 28, 2013 9:09 AM
HIII... THERE IS PROBLEM WITH THIS PROGRAM.IT NOT WORKING AS EXPLAINATION....