Click here to Skip to main content
15,891,703 members
Articles / Web Development / IIS

Dynamic ToolTip

Rate me:
Please Sign up or sign in to vote.
4.31/5 (3 votes)
10 Sep 2007CPOL5 min read 49.3K   29   4
Dynamically toggle ToolTip messages from the client side.

How Can I Dynamically Control Displaying ToolTips from the Client Side?

Have you ever wanted to control whether tooltips are displayed for all controls on a web page at once without having to make a round trip to the server? I ran into the need to do this very thing, and was amazed at how difficult it was to make, what I thought would be a simple task, work as you would expect. I didn't want to write some clunky routine in the code-behind file to handle this because then I would have to "hard-code" references to items in the Presentation layer in the Code-Behind layer. Not to mention having to repost the entire page just to process the routine each time the tooltip display state is changed. I didn't even want to think about what would happen if the need to ever add/remove or rename controls on the page would come about (and don't say that wouldn't happen to you because that's exactly when it's most likely to happen!).

Since there is no "Global" flag I can set to turn tooltips on or off, I needed a way to handle this quickly and gracefully from the client side (browser). I searched Google and all the various ASP.NET sites, and didn't find anything that could solve the particular problem I was having. What follows is the end result of much experimentation and research. I put together this document to help the next person that struggles with this same issue, in the hopes of saving them a whole lot of trouble and stress. Besides, I've certainly benefited from the kindness of other developers who posted their code to help me. Now, it's my turn to give something back to help others.

So the first thing we need is a CheckBox control to allow us to control whether the tooltips are displayed or not.

ASP.NET
<asp:CheckBox ID="cbToolTipMode" runat="server" 
    AutoPostBack="false" Text=" Show Help ToolTips " Checked="false" />

You would add this control to the page wherever you want it to be displayed. Notice the ID tag value (cbToolTipMode) as we will reference this later. The next thing we need is a client-side method to handle setting the tooltip value based on the state of our CheckBox. This will be done with a JavaScript function placed in the page's header section.

JavaScript
<head runat="server">
    <script language="javascript">
        function SetToolTip(Ctrl, TipText)
        {
            if (document.getElementById("cbToolTipMode").checked == true) 
            //Change the control name in this line to match your 

            //CheckBox control name
            {
                if (Ctrl.title == '')
                    Ctrl.title=TipText;
            }
            else
            {
                if (Ctrl.title != '')
                    Ctrl.title='';
            }
        }
    </script>
</head>

Notice that we are checking the checked state of our CheckBox control at the very start of our JavaScript function to control whether we add or remove the tooltip text. Now that we have the JavaScript method to set the tooltip text based on the checked state of our CheckBox, we need some way of telling the page to execute the JavaScript for each control on the page. We'll want this method to be called anytime the mouse enters the borders of the control. So, we'll add an attribute to every control we want to dynamically control the tooltip display state for, by calling this method whenever the mouse enters the control borders.

ASP.NET
<asp:CheckBox ID="cbToolTipMode" runat="server" 
    OnMouseEnter="JavaScript:SetToolTip(this, 'ToolTip Message goes here')"
    AutoPostBack="false" Text=" Show Help ToolTips " Checked="false" />

Notice that we have added an 'OnMouseEnter" event handler to our CheckBox control attributes. This event handler is known to JavaScript, but may not be recognized by the HTML editor you are using:

JavaScript
OnMouseEnter="JavaScript:SetToolTip(this, 'ToolTip Message goes here')"

This is what tells the page to call our JavaScript method when the mouse enters the area of the page where the CheckBox is located. This part of the exercise was fairly simple to achieve; what made this much trickier was when I used this same technique with controls located on a DataGrid. The same technique works on a DataGrid until you want to get the tooltip text from a server-side data source. This is where the rub is, and everything I tried would generate a 'badly formed tag' error or blow up at runtime. I tried various scenarios of building the event handler string to include the server-side tag, but nothing would work. In the end, this is what did work:

JavaScript
OnMouseEnter='<%# String.Format("JavaScript:SetToolTip(this,{0}{1}{2});", 
    ControlChars.Quote, Container.DataItem("Value"), ControlChars.Quote) %>'

The real key to what you see is the 'ControlChars.Quote' located in the Microsoft.VisualBasic namespace, used in conjunction with the String.Format method. This approach allowed me to use the value contained in the bound DataItem column as the input to the JavaScript function. I don't know C#, but I would assume there is a similar method like String.Format. In the old days when I was writing code in 'C', it would have been the sprintf function. Whatever it is in C#, just replace the String.Format method with its C# equivalent and you will hopefully be good to go! I hope this article will make it easier for you to dynamically control tooltip display modes from a page level.

Enjoy!

Background: The Story Behind the Code

The need to toggle tooltips on/off came about while designing a general office software tool. Some users found the tooltip messages annoying (especially since the application GUI is quite intuitive). Unfortunately, there are those users who struggle with anything that plugs into the wall, and it was for their benefit the tooltip messages were added. Regular use of this tool demonstrated, to me personally, the dire need for a way to turn off the tooltip messages with a simple CheckBox control. When I looked at all the ways I could implement such a feature, they all seemed clunky at best, so I set out to find a graceful way to make it happen. You are now reading the solution I came up with to address this simple in concept, but amazingly difficult in implementation, feature.

Using the Code

To use this code to implement dynamic client-side tooltip messages on your web page, simply follow these steps:

  1. Add your CheckBox control to the page.
  2. Add the OnMouseEnter event handler to all page controls you want to control (don't forget to set each control with the tooltip message!).
  3. Change the CheckBox control name in the JavaScript 'SetToolTip' method to match the name you gave your control.

Points of Interest

It still impresses me how many different ways there are to solve a problem in ASP.NET. I tried several different ways to make this idea work, but this one was the magic bullet. Right when I thought I had tried everything, this idea came to me while working on a different problem. Isn't that how it always works?

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralAdding client-side attributes to server controls Pin
Fred_Smith10-Sep-07 22:46
Fred_Smith10-Sep-07 22:46 
GeneralRe: Adding client-side attributes to server controls Pin
drgbg11-Sep-07 14:32
drgbg11-Sep-07 14:32 
Hi Fred,

Thanks for your reply. What you have suggested is certainly one way to add client side methods to server side controls but that method did not address the particular needs of my situation. I was looking to do this in a way that kept my presentation and logic layers separated from each other (a business requirement of my company).

Adding the Attribute code in the Page Load method would certainly work but I have nearly 60 controls on this page that require this method so not only would it be cumbersome to write but difficult to maintain as well. Additionally,this method would also "Hard Code" all the names of the page's buttons, textboxes, labels etc. in the code-behind logic layer (a corporate no-no for me).OMG | :OMG:

Finally, because I needed to toggle the ToolTip display state for all controls on the page and not just the checkbox (that was just an example), this seemed like an efficient and viable solution.

This method has the advantage of keeping all the code in the presentation layer decoupled from the code behind logic layer. So if I need to rename all my controls for some reason (like the boss is having a bad day and wants to take it out on me), I don't have to do anything on the server side like updating the routine that sets the attribute values for each control with the new names. I also save the nanosecond or two required to run the method that sets those attributes from the server side.Big Grin | :-D

This solution solved my particular problem so I would suspect and hope it will help someone else solve theirs. However, to be fair, I suppose the argument could be made that by placing the ToolTip handler in the presentation layer, I have violated the "wall of separation" between Logic and Presentation. I'll concede to that, but I still think this method is the lesser of two evils and the best solution to my particular situation.

Your suggestion demonstrates the point I made at the end of the article that there are several ways to accomplish our goals with the ASP.NET language. It also makes another method available to those that have no requirement to keep the Logic and presentation layers separated.

As for that being the "correct" way to do it, well that is open to debate as I have found there are several ways to accomplish things in programming, each having their own advantages and disadvantages. I think the "correct" way is the way that meets your business rules, timelines and corporate development standards in the least amount of time while still being maintainable. Wow, say that 3 times real fast!!

Cheers back at ya!

The #1 answer from Programmers when their code doesn't work: "I thought I fixed that"

GeneralRe: Adding client-side attributes to server controls Pin
Fred_Smith11-Sep-07 22:52
Fred_Smith11-Sep-07 22:52 
GeneralRe: Adding client-side attributes to server controls Pin
drgbg12-Sep-07 11:09
drgbg12-Sep-07 11:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.