Thursday, January 15, 2009

How to Add a Tooltip to a Dropdown List

It is common in most web pages that whole text in dropdown lists cannot be seen due to width limitation. One solution for this would be adding tooltip for the dropdown, so that when selecting a value from dropdown, whole text will be appear as a tooltip. For most of browsers implementing tooltip on dropdown control is not a big deal. We can simply add tooltip text with 'title' attribute. C# implementation for this would be as follows;

public static void BindTooltip(DropDownList ddl) {
for (int i = 0; i < ddl.Items.Count; i++)
{
ddl.Items[i].Attributes.Add("title", ddl.Items[i].Text);
}
}

But this will not work in Internet Explorer version 6, as IE V6 does not support the 'title' attribute on the <select> control. (IE 7, Firefox … support the 'title' attribute). This is because IE 6 creates a separate window/layer for the <select> tag that is above the rest of the browser window. And Tooltip property is also not working in IE V6.

A partial solution for this issue is add a separate <div> to the form, set the required text, and show/hide that <div> based on mouse activity over dropdown list. Anyway this method will not show the tooltip when selecting an item from the dropdown list. But once you selected an item and move the mouse over dropdown list, it will show the tool tip. Here is the implementation;

DropDown
ddlNames.ID = "DDL_NAMES_ID";
ddlNames.Width = 100;
ddlNames.DataSource = dtNames;
ddlNames.DataTextField = "Full_Name";
ddlNames.DataValueField = "Reg_ID";
ddlNames.DataBind();
ddlNames.Attributes.Add("onmouseover", "showDropDownToolTip(this);");
ddlNames.Attributes.Add("onmouseout", "hideDropDownToolTip();");

DIV
<div id="divDropDownToolTip" style="position:absolute; display:none; background:lightyellow; border:1px solid gray; padding:2px; font-size:8pt; font-family:Verdana;" onMouseOut
="hideDropDownToolTip()">
<span id="toolTipText"></span>
</div>

Java Script
protected override void OnPreRender(EventArgs e)
{
string script = string.Concat(@"
<script type=""text/javascript"" language=""javascript"">
function showDropDownToolTip(ddl){
if ( ddl.options[ddl.selectedIndex].value == '')
return;
var toolTipSpan = document.getElementById('toolTipText');
toolTipSpan.innerHTML = ddl.options[ddl.selectedIndex].text;
var toolTipDiv = document.getElementById('divDropDownToolTip');
toolTipDiv.style.top = window.event.clientY + 140;
toolTipDiv.style.left = window.event.clientX;
toolTipDiv.style.display = 'block';
}

function hideDropDownToolTip()
{
document.getElementById('divDropDownToolTip').style.display = 'none';
}
</script>");

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "NamesToolTipControl", script);
}

1 comment:

Anonymous said...

If you scroll on the page the position of div is calculated wrong...