Currently Browsing: Home » Adding Tooltips to Option Tags

Adding Tooltips to Option Tags

A short while back, Abhilash SR commented on our poll with a question that he had:

Is there any way to show the select box text as [a] tool tip when user moves the mouse down the list?

In other words, Abhilash would like to know whether it’s possible to add tooltips to option tags. Luckily, the answer is yes!

Title Attribute

There are many complicated ways of adding tooltips to the option tag, but the simplest one is accomplished by using the title attribute.

Why do I recommend using the title attribute?

  • It is supported by Internet Explorer.
  • No JavaScript or CSS is required!
  • It only needs a short amount of code.

Thus, adding a tooltip is as easy as:

<option title="Your tooltip here">Your text here</option>

Automating the Process

But, we at Lateral Code want to make this a bit more interesting. In Abhilash’s case, the text that is inside the option tag is exactly what should be used as the tooltip.

As many of us don’t like to waste time copy-pasting this text into the title attribute, why don’t we write a script to do it for us?

Let’s use jQuery to make this very straightforward. Our JavaScript will go through each select element. It will add a title attribute to every option tag inside the given element.

Our algorithm is as follows:

  1. Find the total number of option tags to loop through.
  2. Loop through each tag.
  3. Set the title attribute of the tag to it’s inner HTML.

This yields:

var total = $('select option').length;
var cur;
for ( var i = 0; i < total; i++ )
{
	cur = $('select option:eq(' + i + ')');
	cur.attr( 'title', cur.html() );
}

Remember to import jQuery:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Good luck!

Tags: ,

This entry was posted on Thursday, March 19th, 2009 at 05:00:20. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 Responses to “Adding Tooltips to Option Tags”

  1. ie6 says:

    Title Attribute does not work in IE 6

  2. Danny says:

    an alternate way:
    // show tool tip when scrolling between options
    jQuery(‘select option’).each(function() { this.setAttribute(‘title’, this.text) });

    // Show tool tip after choosing an option
    jQuery(‘select’).attr(‘onmouseover’,function() { this.title = this.options[this.selectedIndex].text; });

  3. jim says:

    This does not work for single-select drop-downs. It HAS to have a size of 2 or more.

Leave a Reply

Want to be notified when someone replies? Subscribe to this post's comment RSS feed.
Any field marked with a * is required.