Web Development  

Dynamic Tooltip with Date Binding and Description

In this article, we will walk through the implementation of a tooltip feature that displays both a date and a detailed description dynamically. This feature is implemented in a table where the tooltip appears when hovering over a specific element, showing the most recent progress along with the associated date. The tooltip content is fetched from a separate database table, and it adjusts dynamically as the user interacts with the table.

Overview

In this example, when the user hovers over an element within a table, a tooltip will appear. The tooltip will contain two key parts:

  1. Date – This is displayed at the top right of the tooltip.

  2. Description – Below the date, a detailed progress description from the database will be displayed.

We will achieve this using the following steps:

  1. Bind the LatestProgress data to the tooltip.

  2. Split the progress data into date and text components.

  3. Adjust the tooltip position based on the mouse location.

HTML Structure for Table with Tooltip

In this section, the tooltip is applied to a table of contact information. Each row has a Status link, which contains a tooltip attribute (data-tooltip). The tooltip is displayed dynamically when the user hovers over the link.

<div class="table_str clear">
    <div class="table-responsive">
        <table cellpadding="0" cellspacing="0" width="100%" border="0">
            <tr>
                <td height="10px"></td>
            </tr>
            <tr>
                <td id="tdmsg" runat="server" align="center" class="Nodata" colspan="2"></td>
            </tr>
            <tr>
                <td height="20px"></td>
            </tr>
            <tr>
                <td>
                    <table cellpadding="0" cellspacing="0" width="100%" border="0">
                        <tr>
                            <td>
                                <asp:DataGrid ID="lead_grid" runat="server" AutoGenerateColumns="False" Width="100%" CellSpacing="0" GridLines="None"
                                    OnItemDataBound="lead_grid_ItemDataBound" AllowPaging="True" PageSize="10" OnPageIndexChanged="NewPage" AlternatingItemStyle-BackColor="#FAFBFE">
                                    <Columns>
                                        <asp:TemplateColumn HeaderText="Status">
                                            <HeaderStyle CssClass="GridHeadL br" />
                                            <ItemStyle CssClass="GridDataL br bb" />
                                            <ItemTemplate>
                                                <a href="javascript:void(0);" onclick="openProgressPopup1('<%# Eval("srno") %>');"
                                                   <%# Eval("LatestProgress") == DBNull.Value || string.IsNullOrEmpty(Eval("LatestProgress").ToString()) 
                                                   ? "" : "data-tooltip=\"" + HttpUtility.HtmlAttributeEncode(Eval("LatestProgress").ToString()) + "\"" %>
                                                   class="GridDataC status-tooltip">
                                                   <%# Eval("Status") %>
                                                </a>
                                            </ItemTemplate>
                                        </asp:TemplateColumn>
                                    </Columns>
                                </asp:DataGrid>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </div>
</div>

<!-- Tooltip div -->
<div id="customTooltip"></div>

CSS for Tooltip Styling

We define the basic styling for the tooltip to make it visually appealing and to ensure that it behaves correctly when displayed near the mouse cursor.

.status-tooltip {
    display: inline-block;    
    position: relative;
    cursor: pointer;
}

#customTooltip {
    position: fixed;
    display: none;
    z-index: 9999;
    background: #fff;
    border: 1px solid #ccc;
    border-radius: 6px;
    padding: 8px 10px;
    font-size: 13px;
    max-width: 260px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
    pointer-events: none;
}

#customTooltip div {
    font-size: 13px;
    line-height: 1.4;
}

#customTooltip div:first-child {
    text-align: right;
    font-size: 11px;
    color: #888;
}

#customTooltip div:nth-child(2) {
    margin-top: 4px;
}

JavaScript for Tooltip Behavior

Now, we implement the functionality for showing and positioning the tooltip dynamically based on the mouse movement. The tooltip will display the date and text components, and it will adjust its position based on the user's cursor.

document.addEventListener("mousemove", function (e) {
    let tooltip = document.getElementById("customTooltip");
    let target = e.target.closest(".status-tooltip");

    if (target) {
        let raw = target.getAttribute("data-tooltip");

        if (!raw || raw.trim() === "") {
            tooltip.style.display = "none";
            tooltip.innerHTML = ""; 
            return;
        }

        let parts = raw.split('|');
        let date = parts.length > 0 ? parts[0] : '';
        let text = parts.length > 1 ? parts.slice(1).join('|') : '';

        if (!date && !text) {
            tooltip.style.display = "none";
            tooltip.innerHTML = "";
            return;
        }

        tooltip.innerHTML = 
            '<div>' + 
                '<div>' + date + '</div>' +
                '<div>' + text + '</div>' +
            '</div>';

        tooltip.style.display = "block";

        let x = e.clientX + 10;
        let y = e.clientY + 10;

        if (x + tooltip.offsetWidth > window.innerWidth) {
            x = e.clientX - tooltip.offsetWidth - 10;
        }

        if (y + tooltip.offsetHeight > window.innerHeight) {
            y = e.clientY - tooltip.offsetHeight - 10;
        }

        tooltip.style.left = x + "px";
        tooltip.style.top = y + "px";
    } else {
        tooltip.style.display = "none";
        tooltip.innerHTML = ""; 
    }
});

document.addEventListener("mouseout", function (e) {
    if (e.target.classList.contains("status-tooltip")) {
        document.getElementById("customTooltip").style.display = "none";
    }
});

Database Binding with Tooltip Content

To implement this feature, you need to retrieve the LatestProgress data from your database and bind it to the grid. We will fetch the data and format it to split the date and description correctly. Here’s the SQL query used to fetch the data and bind it to the table:

SELECT x.*, 
(
    SELECT TOP 1 
        CASE 
            WHEN ISNULL(ProgressDetails, '') = '' 
                 OR CreatedDate = '1900-01-01'
            THEN NULL
            ELSE 
                CONVERT(VARCHAR, CreatedDate, 103) 
                + '|' + 
                REPLACE(REPLACE(ProgressDetails, '''', ''), CHAR(13)+CHAR(10), ' ')
        END
    FROM tablename2 U 
    WHERE U.Srno = x.Srno 
    ORDER BY CreatedDate DESC
) AS LatestProgress
FROM Databasename.dbo.tablename x

In the above query:

  • The LatestProgress column fetches both the CreatedDate and ProgressDetails, which is split into the date and description components using the | separator.

Backend Code to Bind Data

The BindData method in C# handles fetching the data and binding it to the grid. It formats the LatestProgress column appropriately before binding it to the grid.

protected void BindData()
{
    try
    {
        string strqry = @"SELECT x.*, 
        (
            SELECT TOP 1 
                CASE 
                    WHEN ISNULL(ProgressDetails, '') = '' 
                         OR CreatedDate = '1900-01-01'
                    THEN NULL
                    ELSE 
                        CONVERT(VARCHAR, CreatedDate, 103) 
                        + '|' + 
                        REPLACE(REPLACE(ProgressDetails, '''', ''), CHAR(13)+CHAR(10), ' ')
                END
            FROM tablename2 U 
            WHERE U.Srno = x.Srno 
            ORDER BY CreatedDate DESC
        ) AS LatestProgress
        FROM databasename .dbo.tablename x
        WHERE 1 = 1";

        DataSet ds = SqlHelper.ExecuteDataset(SQl_con, CommandType.Text, strqry);

        if (ds.Tables[0].Rows.Count > 0)
        {
            lead_grid.DataSource = ds;
            lead_grid.DataBind();
            nodata.Visible = false;
        }
        else
        {
            lead_grid.DataSource = null;
            lead_grid.DataBind();
            nodata.InnerHtml = "No Data Found!!!";
            lead_grid.Visible = false;
            nodata.Visible = true;
        }
    }
    catch (Exception ex)
    {
        // Handle error
    }
}

Conclusion

In this article, we've demonstrated how to implement a dynamic tooltip with date and description. We discussed how to fetch the necessary data from the database, split it into parts, and display it in a user-friendly tooltip. Additionally, we’ve shown how the tooltip adapts dynamically to the user’s mouse movements and is properly positioned on the screen. This feature greatly improves the user experience by providing additional context and information in an interactive manner.