Wednesday, November 4, 2009

Use Keyboard Shortcuts to Create Tooltips for Forms using jQuery


 
I’ve said this once and I’ll say it again, jQuery is cool. Something on the web that is very helpful to users when filling out HTML forms is for you, the developer, to give them help along the way. I thought it would be cool to use jQuery to show help tooltips when the user clicks on a combination of keys using their keyboard. This article will demonstrate how to capture keyboard events in JavaScript and display help tooltips. 
Before we get started, this example uses the latest version of jQuery which is 1.3.2. That can be downloaded from here. The jQuery Tools and can be downloaded from here
Open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application. Add the following HTML to the Default.aspx page:
 
<table>
            <tr>
                <td>
                    Given Name
                td>
                <td>
                    <input type="text" maxlength="10" id="txtGivenName" />
                td>
                <td>
                    <div id="givenName" style="display:none;" title="G">
                       <img src="info.png" alt="Info" width="16" height="16" />
                        Please supply your given namediv>           
                td>
            tr>
            <tr>
                <td>
                    Surname
                td>
                <td>
                    <input type="text" maxlength="20" id="txtSurname" />
                td>
                <td>
                    <div id="surname" style="display:none;" title="S">
                        <img src="info.png" alt="Info" width="16" height="16" />
                        Please supply your surname. This can only be <b>20b> characters longdiv>       
                td>
            tr>
        table>  
 
The HTML above is quite simple. There’s a table which contains two text boxes. In the cell to the right of the text boxes there’s a
element which contains an image and some useful text if the user gets lost or in unsure of what value to put in the text box. To make a generic piece of JavaScript I’m going to use the title attribute in the
element. I’ll use that as the key to combine with the shift key. The next step is to add the following jQuery code to the section of the page. Ideally JavaScript should go to a separate .js file, however for this example; I’ll keep it in the same page:
 
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">script>
    <script type="text/javascript" language="javascript">
        $(document).ready(function() {
            $(this).keydown(function(e) {
                var evt = e || window.event;
                if (evt.shiftKey) {                   
                    findHelp(evt).fadeIn("slow");
                }
            });
 
            $(this).keyup(function(e) {
                var evt = e || window.event;
                if (evt.shiftKey) {                   
                    findHelp(evt).hide("fast");
                }
            });
        });       
 
        function findHelp(e) {
            var key = (e.keyCode ? e.keyCode : e.charCode);
            return $("div[title=" + String.fromCharCode(key) + "]");
        } 
    script> 
 
In the above code, I’m binding to the document’s keydown and keyup events. On the keydown event, I want to show the tooltip, and on keyup, hide it. 
$(this).keydown(function(e)
$(this).keyup(function(e)
Both pieces of code get information about the event through the argument e. Because I only want this to work when the user holds down the shift key, I’m checking for that through the evt.shiftKey variable. This indicates whether the shift key was pressed when the event fired
var evt = e || window.event;
if (evt.shiftKey)
 
From there I have created a function called findHelp. The sender of the event is passed to this function. I grab either the keyCode or charCode value, and then use that in the jQuery Selector to find the related
element by its title attribute:
 
function findHelp(e) {
var key = (e.keyCode ? e.keyCode : e.charCode);
      return $("div[title=" + String.fromCharCode(key) + "]");
}
 
Running this code now will display the simple form. If you hold down Shift + S or Shift + G it will show and hide the tooltip for each text box.
Before the keydown event and on the keyup event
KeyDownevent_1
During the keydown event
KeyDownevent_2
This is a nice addition for any website that wants to help their users fill out HTML forms. For more information on keyboard events you can go here for more reading. The entire source code of this article can be downloaded over here

Monday, November 2, 2009

Implementing KeyBoard Shortcuts on an ASP.NET Hyperlink Control using jQuery

Implementing KeyBoard Shortcuts on an ASP.NET Hyperlink Control using jQuery
 
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 short article, I will demonstrate how to use jQuery to implement keyboard shortcuts on an ASP.NET Hyperlink control. This article is a sample chapter from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
Note that for demonstration purposes, I have included jQuery code in the same page. Ideally, these resources should be created in separate folders for maintainability.
Let us quickly jump to the solution and see how we can implement KeyBoard shortcut on the Hyperlink control
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Implement KeyBoard Shortcuts on Hyperlinkstitle>
    <script type='text/javascript'
        src='../Scripts/jquery-1.3.2.min.js'>
    script>
   
    <script type="text/javascript">
        $(function() {
            $(document).keyup(function(e) {
                var key = (e.keyCode ? e.keyCode : e.charCode);
                switch (key) {
                    case 49:
                        navigateUrl($('a[id$=linkA]'));
                        break;
                    case 50:
                        navigateUrl($('a[id$=linkB]'));
                        break;
                    case 51:
                        navigateUrl($('a[id$=linkC]'));
                        break;
                    default: ;
                }
            });
            function navigateUrl(jObj) {
                window.location.href = $(jObj).attr("href");
                alert("Navigating to " + $(jObj).attr("href"));
            }
        });       
    script>
 
head>
<body>
    <form id="form1" runat="server">
    <div class="tableDiv">
        <h2>Use Keyboard Keys 1, 2 or 3 to invoke respective
            websitesh2><br />
        <asp:HyperLink ID="linkA" runat="server"
            NavigateUrl="http://www.dotnetcurry.com">
            DotNetCurryasp:HyperLink><br /><br />
        <asp:HyperLink ID="linkB" runat="server"
            NavigateUrl="http://www.sqlservercurry.com">
            SqlServerCurryasp:HyperLink><br /><br />
        <asp:HyperLink ID="linkC" runat="server"
            NavigateUrl="http://www.devcurry.com">
            DevCurryasp:HyperLink><br /><br />
    div>
   
    form>
body>
html>
Implementing a Keyboard shortcut in jQuery is relatively simple as shown here. The code first captures the keyup event and the key is detected using the keyCode or charCode.
$(document).keyup(function(e) {
    var key = (e.keyCode ? e.keyCode : e.charCode);
In the code shown below, if the key = 49, digit 1 is pressed by the user and the first Hyperlink is auto-clicked. Similarly if the key = 50 or 51, then digit 2 or 3 are pressed respectively and the 2nd or 3rd hyperlink is autoclicked. Once the key matches any of the switch case statement, the function navigateUrl() is called passing in the respective hyperlink control object to the function. So if the user pressed 1, the first hyperlink control object is passed to the function as shown below:
switch (key) {
    case 49:
        navigateUrl($('a[id$=linkA]'));
        break;
The navigateUrl function looks like this:
function navigateUrl(jObj) {
    window.location.href = $(jObj).attr("href");
}
The function accepts the hyperlink object and sets the ‘window.location.href’ to the href attribute of the Hyperlink passed in. This is how we invoke actions with shortcut keys.
Tip: keyCode represents the actual key pressed as a numerical value, whereas charCode gives the ASCII/Unicode value of the key press result (for eg: Shift + A). Firefox and other browsers also support ‘e.which’. IE and Opera does not support charCode.
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.
You can see a Live Demo over here. The entire source code of this article can be downloaded over here
 

Tuesday, October 13, 2009

Prevent Cut, Copy and Paste Operations in an ASP.NET TextBox using jQuery


Prevent Cut, Copy and Paste Operations in an ASP.NET TextBox using jQuery
 
In this short article, I will demonstrate how to prevent users from doing Cut, Copy and Paste operations in an ASP.NET TextBox using jQuery. This article is a sample chapter from my upcoming EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls. The chapter content has been modified to publish it as an article. Also please note that for demonstration purposes, I have included JavaScript into the same file. Ideally, these resources should be created in separate folders for maintainability.
The event handling approach in jQuery begins by attaching a handler to an event. The jQuery bind() event method does exactly the same and binds one or more events to a handler. The signature of the bind() method is as follows:
bind(eventType,data,handler)
The parameters of the bind() method are as follows:
eventType is a string holding a JavaScript event type such as click, focus, keyup etc.
data is some optional data you want to pass to the handler
handler is the event handler function which will execute when the event is triggered
Let us quickly jump to the solution and see how we can use the bind() event method to write minimal code to prevent cut, copy and paste operations on the textbox.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Prevent Cut, Copy and Paste Operations in a TextBoxtitle>
    <script type='text/javascript'
    src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
    script>
   
    <script type="text/javascript">
        $(function() {
        $('input[id$=tb1]').bind('cut copy paste'function(e) {
                e.preventDefault();
                alert('You cannot ' + e.type + ' text!');
            });
        });
    script>
head>
<body>
    <form id="form1" runat="server">
    <div class="bigDiv">
        <h2>Prevent Cut, Copy and Paste Operations in a TextBoxh2>
        <asp:TextBox ID="tb1" runat="server"
            Text="Text which cannot be copied/cut/pasted" 
            ToolTip="Try Copy/Cut/Paste in textbox"/>       
    div>
    form>
body>
html>
Observe how convenient it is to use jQuery to list multiple events (cut, copy, paste) together and bind it to a handler as shown below.  
$('input[id$=tb1]').bind('cut copy paste'function(e) {});
 
If the user performs any of these events on the textbox (tb1), the default behavior is prevented using e.preventDefault() and the user is alerted with a message. The e.type describes the type of event performed.
$('input[id$=tb1]').bind('cut copy paste'function(e) {
      e.preventDefault();
      alert('You cannot ' + e.type + ' text!');
});
 
CutCopyPaste
This piece of ‘minimal’ code handles a typical requirement where you are asked to ‘confirm’ an email address and want the user to type it manually, instead of copying and pasting it.
Note: Text can be edited in this textbox, but cut/copy/paste actions are prevented
This demo has been tested on IE7, IE8, Firefox 3, Chrome 2 and Safari 4.

Thursday, October 8, 2009

Limit Number Of Characters In an ASP.NET Multiline TextBox using jQuery

Limit Number Of Characters In an ASP.NET Multiline TextBox using jQuery
 
This article shows you how to limit characters entered in an ASP.NET Multiline TextBox. The ASP.NET Multiline TextBox ignores the MaxLength property. So one of the ways of solving this requirement is to use Client Script and detect if the maximum character limit of the Multiline TextBox has been reached. I will be showing a common technique adopted by developers to solve this requirement. I will then explain why this technique is not user friendly and how to improve on it.
This article is a sample chapter from my upcoming EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls. The chapter content has been modified to publish it as an article. Also please note that for demonstration purposes, I have included both the JavaScript and CSS into the same file. Ideally, these resources should be created in seperate folders for maintainability.
A common technique adopted by developers is to capture the textbox keyup event and calculate the number of characters in the textbox, as the user types in it. If the character exceeds the limit of the textbox (in our case 50 characters), the additional characters entered by the user is disallowed.  The code is as shown below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Limit Characters in a Multiline TextBoxtitle>
    <script type='text/javascript'
    src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
    script>
 
    <script type="text/javascript">
        $(function() {
            var limit = 50;
 
            $('textarea[id$=tb1]').keyup(function() {
                var len = $(this).val().length;
                if (len > limit) {
                    this.value = this.value.substring(0, limit);
                }
                $('#spn).text(limit - len + " characters left");
            });
        });
    script>
head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="tb1" runat="server" TextMode="MultiLine"/><br /> 
        <span id="spn ">span>     
    div>
    form>
body>
html>
Observe how we are selecting the control using textarea in the code shown above $('textarea[id$=tb1]'). This is as the ASP.NET Multiline TextBox renders as a textarea.
Although the solution given above restricts the user from entering more than 50 characters, this behavior can be confusing for users who may not realize that they have reached the TextBox limit. Instead of disallowing extra characters, a slick way of handling this requirement would be to visually indicate to the user when the textbox limit has been exceeded. Then before submitting the form, give the user a chance to remove the extra text. The code shown below changes the background color of the textbox to red when the textbox limit is exceeded. The user is also prevented from submitting the form.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Limit Characters in a Multiline TextBoxtitle>
    <script type='text/javascript'
    src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
    script>
    <style type="text/css">
    .exceeded{
        background-color:red;
    }
    style>
   
    <script type="text/javascript">
        $(function() {
            var limit = 50;
            var tb = $('textarea[id$=tb1]');
            $(tb).keyup(function() {
                var len = $(this).val().length;
                if (len > limit) {
                    //this.value = this.value.substring(0, 50);
                    $(this).addClass('exceeded');
                    $('#spn').text(len - limit + " characters exceeded");
                }
                else {
                    $(this).removeClass('exceeded');
                    $('#spn').text(limit - len + " characters left");
                }
            });
 
            $('input[id$=btnSubmit]').click(function(e) {
                var len = $(tb).val().length;
                if (len > limit) {
                    e.preventDefault();
                }
            });
        });
    script>
head>
<body>
    <form id="form1" runat="server">
    <div class="smallDiv">
        <h2>Type into this textbox which accepts 50 characters overallh2>
        <asp:TextBox ID="tb1" runat="server" TextMode="MultiLine"/><br />
        (This textbox accepts only 50 characters) <br />
        <span id="spn">span> <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit"/>
        <span id="error">span>
        <br /><br />
        Tip: Clicking on the Submit button when number of characters are
        less than 50, results in a postback to same page. If you exceed 50
        characters, the exceeded characters are printed below the textbox
        and a postback is prevented.
    div>
    form>
body>
html>
When the number of characters exceeds the textbox limit, we add the exceeded class to the textbox, which turns the textbox background to red, indicating the user that the limit has been exceeded. The result is shown here:
LimitExceeded
When the user tries and submits the form now, the length of the TextBox is calculated and the user is prevented from submitting the form, since the textbox exceeds the permissible length. 
When the user removes the extra text, the exceeded class is removed. The result is shown here:
RemoveExceeded
The form can now be submitted. You can see a Live Demo here . This demo has been tested on IE7, IE8, Firefox 3, Chrome 2 and Safari 4.

Tuesday, October 6, 2009

Using jQuery To Create Stunning Tooltips in your ASP.NET Applications

Using jQuery To Create Stunning Tooltips in your ASP.NET Applications


jQuery Tools is a collection of the most important user interface components for the web. These are tabs and accordions, tooltips, overlays, exposing effects and scrollables. They can dramatically improve the usability and responsiveness of your site. They mainly focus on presenting information and visual appeal. After all, this is exactly what most websites desperately want: to present their content to the reader in an easy and visually pleasing manner.
I’ll be focusing some future articles on these tools, but this article will concentrate on how to create stunning tooltips using this plugin. The end result in this article will show you how to create these tooltips using dynamic data by using jQuery’s Ajax functionality. The end result will look something like this:
ToolTip
Before we get started, this example uses the latest version of jQuery which is 1.3.2. That can be downloaded from here. The jQuery Tools and can be downloaded from here
The jQuery Tools plugin has quite a few options when it comes time to configuration, but the one you should not forget is the tip attribute. This jQuery selector selects the tooltip element being used. The attribute that will allow you to position the tooltip is funnily enough called position. The position property specifies the position in relation to the trigger element. For example, a value of 'bottom center' will place the tooltip on the bottom edge of the trigger, centred horizontally. Other values are:

  • top center, top right, center right, bottom right, bottom left, center left and top left

To make this real, instead of showing this tooltip against static data such as images, I’m going to use jQuery’s Ajax functionality to query the server for a list of running processes. Okay let’s gets started. Open Visual Studio 2008 and create a new Web Application. First off add a new class to the project and call it ProcessInfo. This class will hold information about the process. Add the following code to the class:
C#
public class ProcessInfo
{
public string ProcessName { get; set; }
      public string MainWindowTitle { get; set; }
      public long PagedMemorySize64 { get; set; }
}
VB.NET
Public Class ProcessInfo
Private privateProcessName As String
Public Property ProcessName() As String
      Get
            Return privateProcessName
      End Get
      Set(ByVal value As String)
            privateProcessName = value
      End Set
End Property
       Private privateMainWindowTitle As String
       Public Property MainWindowTitle() As String
             Get
                   Return privateMainWindowTitle
             End Get
             Set(ByVal value As String)
                   privateMainWindowTitle = value
             End Set
       End Property
       Private privatePagedMemorySize64 As Long
       Public Property PagedMemorySize64() As Long
             Get
                   Return privatePagedMemorySize64
             End Get
             Set(ByVal value As Long)
                   privatePagedMemorySize64 = value
             End Set
       End Property
End Class
The next step is to open the Default.aspx.cs file and add the following code:
C#
[WebMethod]
public static List<ProcessInfo> GetRunningProcesses()
{
var query = (from p in System.Diagnostics.Process.GetProcesses()
                  select new ProcessInfo
                  {
                        ProcessName = p.ProcessName,
                        MainWindowTitle = p.MainWindowTitle,
                        PagedMemorySize64 = p.PagedMemorySize64                            
}).ToList();
return query;
} 
VB.NET
_
Public Shared Function GetRunningProcesses() As List(Of ProcessInfo)
Dim query = ( _
    From p In System.Diagnostics.Process.GetProcesses() _
    Select New ProcessInfo With {.ProcessName = p.ProcessName, .MainWindowTitle = p.MainWindowTitle, .PagedMemorySize64 = p.PagedMemorySize64}).ToList()
Return query
End Function
The code above will be called by jQuery’s Ajax function. It returns a list of running process on the machine thanks to the Process object. The Process class provides access to local and remote processes. The LINQ query will return a generic list of ProcessInfo objects that will be used to create the tooltips. The next step is to add the JavaScript. Open the Default.aspx page and add the following jQuery code to the section of the page. Ideally JavaScript should go to a separate .js file, however for this example; I’ll keep it in the same page:
<script language="javascript" type="text/javascript" src="Scripts/jquery-1.3.2.js">script>
<script language="javascript" type="text/javascript" src="http://cdn.jquerytools.org/1.1.1/jquery.tools.min.js">script>
    <script language="javascript" type="text/javascript">
        function showToolTip() {           
            $("#results span[title]").tooltip({
                position: "center right",     
                opacity: 0.7,
                tip: "#demotip",
                effect: "fade"
            });           
        }

        $(document).ready(function() {
            $("#btnSearch").click(function() {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/GetRunningProcesses",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: true,
                    success: function(msg) {
                        var processInfo = msg.d;
                        $("#results").text("");
                        for (var i = 0; i < processInfo.length; i++) {
                            // create the title for each item
                            var title = "Process Name: " +
                                        processInfo[i].ProcessName +
                                        "<BR>" +
                                        "Paged Memory Size64: " +
                                        processInfo[i].PagedMemorySize64;                           
                            $("#results").append("">" +
                            processInfo[i].ProcessName +
                            "

"
);
                        }
                    }
                });
            });
        });   
    script>

In the code above I am binding to the input button’s click event. When the user clicks the button, it will execute the WebMethod GetRunningProcesses. A generic list containing the ProcessInfo data will be returned in the msg.d argument. For each process returned, a span tag will be appended in the div element. When the user hover’s their mouse over the tag, the JavaScript function showToolTip will run. This function is responsible for displaying the tooltip:
function showToolTip() {           
$("#results span[title]").tooltip({
position: "center right",     
            opacity: 0.7,
            tip: "#demotip",
            effect: "fade"
      });           
}
Using jQuery’s selectors the tooltip will find the related span tag to trigger the tooltip. The tool looks for the element that is placed next to the tooltip to be the tooltip. The return value is a jQuery object associated with the selection.   The result is a stunning tooltip as the screen shot below shows:
ToolTip
The information in the tooltip can be configured as it’s just HTML. So if you want you can display a nice image to the user so they’ll be able to associate the process by the icon. The background image of the tooltip is configurable too. The styling for the tooltip is below:

#demotip {
          display:none;
          background:transparent url(http://flowplayer.org/tools/img/tooltip/black_arrow.png);
          font-size:12px;
          height:70px;
          width:160px;
          padding:25px;
          color:#fff;    
}

This is a nice addition to your jQuery ensemble. The entire source code of this article can be downloaded over here