Building custom tooltips using Javascript

Now a days most of the website developers come across building custom tooltips for their applications. There are many third party controls available for ASP.NET developers with tooltip control features. But here I will showcase on building custom tooltip using Javascript.

All we need for this is declare a DIV tag which is going to act as Tooltip in your web page. And also you can define controls which ever you want to show them as tooltip in side DIV tag. Apply the DIV tag position style as 'absolute' position. Below is an example what I've used to show it as Tooltip card:
<div id="pinCard" style="background-color: #FFFFCC; border: thin solid #808000;
  position:absolute; visibility:hidden; width:200px">
  Hello, Mr.Srinivas
 <b r /> <b r />
Your booking number is: &nbsp;
<div id="bkValue"></div>
Now the tooltip card is ready. Our next step is displaying the tooltip on mouse move on any SPAN tag content and hide tooltip on mouse out from SPAN tag. It's similar to below example:
Booking Number:&nbsp;<span onmousemove="fnShowTooltip(this,event)"
 onmouseout ="fnHideTooltip(this)">100001</span><br /><b r />
    Booking Number:&nbsp;<span onmousemove="fnShowTooltip(this,event)" 
 onmouseout="fnHideTooltip(this)">100002</span><br /><b r />
    Booking Number:&nbsp;<span onmousemove="fnShowTooltip(this,event)" 
 onmouseout="fnHideTooltip(this)">100003</span><br /><b r />
    Booking Number:&nbsp;<span onmousemove="fnShowTooltip(this,event)" 
 onmouseout="fnHideTooltip(this)">100004</span><br /><b r />
    Booking Number:&nbsp;<span onmousemove="fnShowTooltip(this,event)" 

The javascript function fnShowTooltip will show tooltip and fnHideTooltip is used to hide the tooltip. Below is the code for these two js funtions:
       function fnShowTooltip(control,e) {
           document.getElementById("bkValue").innerHTML = "<b>" + control.innerHTML + "</b>";
           var card = document.getElementById('pinCard');
  = (e.clientX + 10) + "px";
  = (e.clientY + 10) + "px";
  = 'visible';  

       function fnHideTooltip(e) {
           var card = document.getElementById('pinCard');
  = 'hidden';           
Optionally, we can apply some style to span tags like:
That's it! Run your web page with above sample codes and move the mouse over any of the booking numbers, you'll get to see tooltip card which is build from DIV tag as shown below:

Hope this helps, who are looking for custom tooltips.

No comments:

Powered by Blogger.