Search code examples
javascriptasp.netcsstooltip

Display div (tooltip) in correct position on hover


I have a form with a GridView and a table with images in it. The images have a div (tooltip) that shows up onmouseover. The div displays at the very bottom of the form and not close by the images like I want it to. How can I have the div display below and to the left of the image?

ascx code:

<table>
<tr>
<asp:Label ID="Tools" runat="server" Text="Tools" />
<div style="display: inline; position:relative; ">
<asp:ImageButton ID="CSV" ToolTip="CSV" runat="server" ImageUrl="document-excel-csv-icon.png"
OnClick="BtnCSV_Click" onmouseover="showToolTip_CSV()" onmouseout="hideToolTip_CSV()" />
<div id="tooltip-CSV" role="tooltip" class="tooltip" style="display: none;" >
 <label ID="CSV_label">CSV</label>
</div>
</div>
<div style="display: inline; position: relative;">
<asp:ImageButton ID="PDF" ToolTip="PDF" runat="server" ImageUrl="document-pdf-icon.png" 
OnClick="BtnPDF_Click" onmouseover="showToolTip_PDF()" onmouseout="hideToolTip_PDF()" />                            
<div id="tooltip-PDF" role="tooltip" class="tooltip" style="display: none;">
<label ID="PDF_Label">PDF</label>
</div> 
</div>
</td>
</tr>        
</table>

javascript

<script type="text/javascript">
function showToolTip_CSV() {
    document.getElementById("tooltip-CSV").style.display = "inline-block";
}    
function showToolTip_PDF() {
         document.getElementById("tooltip-PDF").style.display = "inline-block";
}   
function hideToolTip_CSV() {
     document.getElementById("tooltip-CSV").style.display = "none";
 }
function hideToolTip_PDF() {
     document.getElementById("tooltip-PDF").style.display = "none";
 }
</script>

css

.tooltip
{        
width: 30px;
padding: 10px;    
position: absolute;
left: 10px;
bottom: -20px;
background: #f4f0ec;
border: 2px solid #e0cfc2;
border-radius: 6px;  
}

Solution

  • One simple approach is to set the coordinates of your pop-up to the coordinates of the element that is clicked. Several good solutions are discussed here: Retrieve the position (X,Y) of an HTML element

    Another approach, the one I prefer, involves embedding a tooltip div inside each div that contains an image. The parent div of the image will have relative position to set a positioning context (http://www.impressivewebs.com/absolute-position-css/). Then when you use absolute positioning, the tooltip is positioned relative to the div that contains the image.