JavaScript ToolTip

Most of the time we came across using the ToolTips. In .net most of the controls have ToolTip property. However one disadvantage you find in this tooltip is that it won’t persist for a long time. It will appear for a short time when you mouse hover on the particular control. Here we are going to implement a simple JavaScript ToolTip:

Here i am demonstrating a ToolTip for a Label control and a Button control.

Inside the <head> tag add the JavaScript

<script language=”javascript” type=”text/javascript”>
function showToolTip(text) {
var toolTip = document.getElementById(“spnToolTip”);
toolTip.style.top = window.event.clientY + 10;
toolTip.style.left = window.event.clientX;
toolTip.innerHTML = text;
toolTip.style.visibility = “visible”;
toolTip.style.background = ‘lightyellow’;
}

function showToolTipColorBG(text,color) {
var toolTip = document.getElementById(“spnToolTip”);
toolTip.style.top = window.event.clientY + 10;
toolTip.style.left = window.event.clientX;
toolTip.innerHTML = text;
toolTip.style.visibility = “visible”;
toolTip.style.background = color;
}

function hideToolTip() {
document.getElementById(“spnToolTip”).style.visibility = “hidden”;
}
</script>

The first function ‘showToolTip()’ is for the label control. We are passing the text to display in the ToolTip as parameter. In the second function showToolTipColorBG(), we are passing two parameters, first the text for the tool tip and second is color of the tool tip. The second function is for the button control.

Add the below span tag in the HTML:

<span id=”spnToolTip” style=”BORDER-RIGHT: gray 1px solid; PADDING-RIGHT: 2px; BORDER-TOP: gray 1px solid; PADDING-LEFT: 2px; FONT-SIZE: 8pt; Z-INDEX: 111; BACKGROUND:lightyellow; VISIBILITY: hidden; PADDING-BOTTOM: 2px; BORDER-LEFT: gray 1px solid; PADDING-TOP: 2px; BORDER-BOTTOM: gray 1px solid; FONT-FAMILY: Verdana; POSITION: absolute” onmouseout=”hideToolTip()”>
</span>

In the Page_Load write

if (!IsPostBack)
{
lbl.Attributes.Clear();
lbl.Attributes.Add(“onMouseOver”, “showToolTip(‘Label ToolTip’)”);
lbl.Attributes.Add(“onMouseOut”, “hideToolTip(‘this’)”);

btn.Attributes.Clear();

btn.Attributes.Add(“onMouseOver”, “showToolTipColorBG(‘Button ToolTip’,’green’)”);
btn.Attributes.Add(“onMouseOut”, “hideToolTip(‘this’)”);
}

lbl is the Label control and btn is the Button control.