Implementing KeyBoard Shortcuts in ASP.NET applications using jQuery

Posted by: Suprotim Agarwal , on 6/4/2009, in Category jQuery and ASP.NET
Views: 53897
Abstract: Continuing my journey of exploring ASP.NET with jQuery, I will show you how to implement Keyboard Shortcuts in ASP.NET applications using jQuery, without using any C# or VB.NET code.
Implementing KeyBoard Shortcuts in ASP.NET applications using jQuery
 
Last year, I had written an article Going Mouseless - Implementing Keyboard Shortcuts in ASP.NET 2.0 Using Javascript where I had used the ClientScript.RegisterClientScriptBlock to register a client script block to the top of the rendered page using a type, key, and script literal. The client script would intercept each keystroke and then take action based on the key pressed. Continuing my journey of exploring ASP.NET with jQuery, in this article, I will show you how to implement Keyboard Shortcuts in ASP.NET applications using plain jQuery, without using any C# or VB.NET code.
Popular Web apps like Gmail and Windows Live Mail feature Keyboard shortcuts, which help you save time by executing common operations using the Keyboard, without having to switch between the keyboard and mouse. In this article, we will implement Keyboard shortcuts in our own ASP.NET applications using jQuery. Let us get started.
Note:  I assume you are familiar with jQuery. If you are new to jQuery, then before moving ahead, I would recommend you to check out Using jQuery with ASP.NET - A Beginner's Guide. Please do take a note that this article uses jQuery’s current version - jQuery 1.3.2 and jQuery 1.3.2 Visual Studio 2008 Autocomplete documentation.
Step 1: Create an ASP.NET website. Add a master page to the application(MasterPage.master). Also create 4 pages that will be using this master page: Default.aspx, Page1.aspx, Page2.aspx and Page3.aspx.
Step 2: In the Default.aspx, drag and drop 3 LinkButton to the form. Rename these LinkButton’s as Page 1, Page 2 and Page 3 respectively. The markup would be similar to the following:
 <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div>
    <asp:LinkButton ID="lbPage1" runat="server" PostBackUrl="Page1.aspx">
    Page 1</asp:LinkButton><br />
    <asp:LinkButton ID="lbPage2" runat="server" PostBackUrl="Page2.aspx">
    Page 2</asp:LinkButton><br />
    <asp:LinkButton ID="lbPage3" runat="server" PostBackUrl="Page3.aspx">
    Page 3</asp:LinkButton><br />           
</div>
</asp:Content>
Step 3: Go back to your MasterPage.master and add the following jQuery code to the <head> section of the page. Ideally all scripts should go to a separate .js file, however for understanding purposes; we will keep it in the same page. The code would look similar to the following:
<head runat="server">
    <title>KeyBoard ShortCuts</title>
        <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $(document).keyup(function(event) {
                var key = event.keyCode || event.charCode || 0;
                if (key == 49) { // Page One Press 1
                    eval($("[id$='lbPage1']").attr("href"));
                } else if (key == 50) { // Page Two Press 2
                    eval($("[id$='lbPage2']").attr("href"));
                } else if (key == 51) { // Page Three Press 3                 
                    eval($("[id$='lbPage3']").attr("href"));
                } else if (key == 52) { // Alert Press 4
                    $("[id$='btnAlert']").trigger('click');
                }
            });
        });
    </script>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
In the code above, we are binding to the keyup event and performing different actions depending on the key pressed by the user. The keyup event fires when a key on the keyboard is released. The Key is captured using the event.keyCode which returns the Ascii value of the key. We then take action depending on the Ascii code returned. Here 1 returns Ascii 49, 2 returns 50, 3 returns 51 and 4 returns 52.
There are two very important points to observe here –
1. Accessing controls in Master Content Pages using $("[id$='lbPage1']". The trick is to use the '$='operator to match the end of the id string as in ctl00_ContentPlaceHolder1_lbPage1.
2. The usage of eval() – Let me explain why eval() is required. The link button gets rendered as
<a id="ctl00_ContentPlaceHolder1_lbPage1" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$ContentPlaceHolder1$lbPage1&quot;, &quot;&quot;, false, &quot;&quot;, &quot;Page1.aspx&quot;, false, true))"> Page 1</a>
Observe the JavaScript code in the href which is responsible for a postback when the LinkButton is clicked. So in order to invoke this code using our KeyBoard Shortcut, we use eval(), which executes the JavaScript code and emulates a click().
Step 4: The last step is to test the Keyboard shortcut on the Default.aspx page by pressing 1, 2 or 3 to navigate to Page1 , Page2 or Page 3 respectively. Similarly press ‘4’ to refresh the Default.aspx page.
Cool, isn’t it! The main focus of this article was to demonstrate how to use jQuery in ASP.NET pages and create a simple Keyboard shortcut functionality. However once you understand how to use this effectively, the possibilities are endless. Gmail, Live Mail, Yahoomail are three good examples where keyboard shortcuts are being used to improve user interactiveness with the application. Mail back and let me know how you used this code in your application.

The entire source code of this article can be downloaded from here.

I hope you liked the article and I thank you for viewing it. If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email

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 anup hosur on Saturday, June 6, 2009 11:12 PM
great article.. i saw this in asp.net of your site, but this is even better..
Comment posted by Mark on Sunday, June 14, 2009 11:51 AM
In your last case you trigger a click but in those before, you use `eval' -- which is bad. If you ever see yourself using eval, then you've probably written JS code poorly and need to think about it again. To emulate a clikc on a matched element, you can just do $("foobar").click()
Comment posted by ashisah on Thursday, August 6, 2009 7:25 AM
i want whole source code in mail and this code is very good
Comment posted by ashisah on Thursday, August 6, 2009 7:57 AM
i want whole source code in mail and this code is very good
Comment posted by Suprotim Agarwal on Tuesday, August 11, 2009 1:23 AM
Ashisah: The entire source code is available to Registered user or Newsletter subscriber.The link has been added in this article.
Comment posted by prabhu on Sunday, September 6, 2009 4:54 AM
I Found the Source Code in Your Website.so Thanks, this is most populate Code