Create new account I forgot my password    

Using jQuery in an ASP.NET MVC application To Create Stunning Tooltips - Version 2
Rating: 7 user(s) have rated this article Average rating: 3.1
Posted by: Malcolm Sheridan, on 1/29/2010, in category "ASP.NET MVC"
Views: this article has been read 19054 times
Abstract: The following article demonstrates how to use jQuery with ASP.NET MVC to create stunning tooltips.

Using jQuery in an ASP.NET MVC application To Create Stunning Tooltips - Version 2
 
Last year I wrote an article on How To Create Stunning Tooltips With jQuery And ASP.NET. Well recently I had to code tooltips by hand and realised the code to do this is quite small and simple. The trick is to dynamically create a floating <div> tag next to where the mouse currently is. To find out the current location of the mouse, the trick is to query the event object that is passed to your event handler. From there you can retrieve the pageX and pageY coordinates. These will give you the top and left mouse position relative to the document. 
For this example I'll be displaying the alternate text that accompanies the <a> element. This information resides in the title attribute. But when the user hovers their mouse over the <a> element, I want to substitute the tooltip with a custom one. Sounds hard but really it's not. The end result will look like this:





EndResult
To demonstrate this I’ve created an ASP.NET MVC application. So as not to depend on a database, I'm going to display all the Windows Services that are running on my machine. Each custom tooltip will display the description and name of the Windows Service. The data will be returned to the client as JSON which can easily be consumed by jQuery. 
To get our custom tooltip to display instead of the default tooltip, I need to dynamically display a <div> element next to each <a> element. In order to achieve the location of the mouse's position, I will bind an event handler to the mouseover and mouseout events. From there I can use the event object to query the X and Y coordinates. I'll start by showing you how to query for the Windows Services. The action below returns a JsonResult:
C#
public ActionResult Index()
{
      var mcServices = new ManagementClass("Win32_Service");
      var services = (from p in mcServices.GetInstances().OfType<ManagementObject>()
                        select new ServiceData
                        {
                            Description = p.GetPropertyValue("Description") as string,
                            Caption = p.GetPropertyValue("Caption").ToString()
                        }).ToList();
      return View(services);
}       
VB.NET
 Public Function Index() As ActionResult
      Dim mcServices = New ManagementClass("Win32_Service")
       Dim services = ( _
            From p In mcServices.GetInstances().OfType(Of ManagementObject)() _
            Select New ServiceData With {.Description = TryCast(p.GetPropertyValue("Description"), String), .Caption = p.GetPropertyValue("Caption").ToString()}).ToList()
       Return View(services)
End Function         
Nothing fancy about that. Now for the fun part! Here's the complete code below which I will explain afterwards:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" language="javascript" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(function() {
            var title = "";
            var toolTip = $("<div id=\"toolTipCss\"></div>")
                                .appendTo("body")
                                .hide();
            $("#listServices").bind("mouseover mouseout", function(event) {
                var link = $(event.target).closest("a");
                if (link.length == 0) {
                    return;
                }
 
                var linkFound = link[0];
                if (event.type == "mouseover") {
                    title = linkFound.title;
                    linkFound.title = "";
                    toolTip.html("<div class=\"toolTipText\">" + title + "</div><div class=\"toolTipText\"><br />" + linkFound.text + "</div>")
                          .show()
                          .css(
                          {
                              top: event.pageY - 40,
                              left: event.pageX + 10,
                              opacity: 0
                          })
                          .animate(
                          {
                              left: "+=25",
                              opacity: 1
                          }, "7000");
                }
 
                if (event.type == "mouseout") {
                    linkFound.title = title;
                    toolTip.animate(
                        {
                            opacity: 0
                        }, "5000");
                }
            });
        });
    </script>
Ok let's go through the code to see how it works. The first step is to create the <div> element dynamically, append it to the bottom of the <body> tag and hide it:
var toolTip = $("<div id=\"toolTipCss\"></div>")
                                .appendTo("body")
                                .hide();
 
The Windows services list will be a bunch of <a> elements contained inside of a <div> element. Each <a> will contain a title. The title will contain the description of the service. For an action to happen when the user hovers their mouse over each <a> element, I'm binding an event handler to the mouseover and mouseout events:
$("#listServices").bind("mouseover mouseout", function(event) {
 
The first step is to find the closest <a> element to the mouse. This is achieved by using the closest function. If an anchor is found, I am assigning it to a variable, otherwise the processing stops:
 
var link = $(event.target).closest("a");
if (link.length == 0) {
      return;
}
var linkFound = link[0];
 
The next step is to find the event that was triggered. This is done by querying the event.type. If the mouseover event occurred, I take the closest <a> element and copy the text and title into the <div> element. To position it I am setting the top and left CSS elements from the pageX and pageY values. I finish it off by animating the tooltip sideways:
 
if (event.type == "mouseover") {
      title = linkFound.title;
      linkFound.title = "";
      toolTip.html("<div class=\"toolTipText\">" + title + "</div><div class=\"toolTipText\"><br />" + linkFound.text + "</div>")
            .show()
            .css(
            {
                  top: event.pageY - 40,
                  left: event.pageX + 10,
                  opacity: 0
            })
            .animate(
            {
                  left: "+=25",
                  opacity: 1
            }, "7000");
}
 
The following two lines above temporarily remove the <a> elements title text:
 
title = linkFound.title;
linkFound.title = "";
 
This is required otherwise the elements default tooltip will be displayed. Yuck! When the user moves the mouse away from the <a> element, the mouseout event will be triggered. I add the anchors title back and set the opactity of the <div> element back to zero, effectively hiding it:
 
if (event.type == "mouseout") {
      linkFound.title = title;
      toolTip.animate(
            {
                  opacity: 0
            }, "5000");
}
The end result is a nice tooltip for your project. The styling of the tooltip is handled by CSS, so if you want to change it to something else, you can easily do that. The entire source code of this article can be downloaded over here
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email

Malcolm Sheridan is an independent contractor who has been working with Microsoft technologies since VB4. Malcolm has worked with .NET since its inception and thoroughly enjoys ASP.NET.









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback

Post your comment
Name:
E-mail: (Will not be displayed)
Comment:
Insert Cancel

NEWSLETTER