Using jQuery in an ASP.NET MVC application To Create Stunning Tooltips - Version 2

Posted by: Malcolm Sheridan , on 1/29/2010, in Category ASP.NET MVC
Views: 60761
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

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
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Altaf Khatri on Tuesday, February 1, 2011 4:53 PM
In ASP.NET MVC application, sometimes we need to find element with special characters like period/dot/. and parenthesis([]). This article describes the solution to find elements in jquery:



down vote  This article describes how to find element with special characters like dot/period/. and parenthesis in jquery:

http://www.altafkhatri.com/Technical/Javascript/Jquery/Find_Element_By_Special_Character_ByName_ById
Comment posted by Sandesh on Monday, February 7, 2011 1:09 AM
Some of the interesting jquery and asp.net integration can be found <a href="http://www.cmsstores.com/using-jquery-in-asp-net-application-and-its-advantages/"> here</a>
Comment posted by Balaji Karpurapu on Tuesday, April 19, 2011 8:47 AM
Good Post!...

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook