CSS tooltip fails to display

I'm having trouble with my code as the tooltip is not showing up! Interestingly, when I tested the CSS on a static table, it worked perfectly.

Essentially, the table in the code is dynamically created using information from an array for headers and data from an associative array.

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>Json Array to Html Table</title>
    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <style>
        .day {
            position: relative;
        }

        .day .tooltiptext {
            visibility: hidden;
            width: 120px;
            background-color: #555;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 5px 0;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            margin-left: -60px;
            opacity: 0;
            transition: opacity 1s;
        }

        .day .tooltiptext::after {
            content: "";
            position: absolute;
            top: 100%;
            left: 50%;
            margin-left: -5px;
            border-width: 5px;
            border-style: solid;
            border-color: #555 transparent transparent transparent;
        }

        .day:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }
    </style>
</head>

<body>
    <p><br/><br/></p>
    <div id="tblContainer"></div>   
</body>

<script>
    $(document).ready(function(){
        // Table Headers
        var headers = ["S", "M", "T", "W", "T", "F", "S"];  

        // Json Array
        var myData = [
             {"Date":"25/12/2016", "MonthName":"January","DataDiff":"7","MonthDays":"31"},
             {"Date":"29/01/2017", "MonthName":"February","DataDiff":"3","MonthDays":"28"},
             {"Date":"26/02/2017", "MonthName":"March","DataDiff":"3","MonthDays":"31"},
             {"Date":"26/03/2017", "MonthName":"April","DataDiff":"6","MonthDays":"30"}
            ];              

        // Create Table
        var cityTable = makeTable_HeadersOnly($('#tblContainer'), headers, "Planner", 6 );

        // Append data from Json array
        appendTableRowsJsonFile(cityTable, myData); 
    });

    // Make Table just with headers
    function makeTable_HeadersOnly(container, data, id, nrTimes) {
        var table = $('<table id=' + id + '/>');
        var row   = $('<thead/>');

        row.append($('<tr/>'));

        // First Column
        row.append($('<th/>').text(""));

        // Generates the columns
        for (i=1; i <= nrTimes; i++) {
            $.each(data, function(colIndex, c) { 
                row.append($("<th/>").text(c));
            });
        }
        table.append(row);

        // tbody
        row   = $('<tbody/>');
        table.append(row);

        return container.append(table);
    }

    // append table row from json file
    function appendTableRowsJsonFile($table, jdata) {
        var day = 1;
        var diff = 0;
        var daysMth = 0;
        var data = "";
        $.each(jdata, function(key, value){
            // Month
            let tr = $("<tr/>");    
            tr.append($("<td/>").text(value.MonthName));

            // Fill days
            diff = parseInt(value.DataDiff);
            daysMth = parseInt(value.MonthDays);
            for (i = 1; i <= 42; i++) { 
                if (i <= diff ){
                    tr.append($("<td/>").text(''));
                } else if (i <= diff + daysMth) {       
                    day = i - diff;
                    tr.append($('<td/ class="day" data-date="show date">').text(day));
                } else{
                    tr.append($("<td/>").text(''));
                }
            }
            $table.find('tbody').last().append(tr);             
        });
    }

    // Tooltip - class 'day'
    $('.day').hover(function(e){
        alert('Tooltip');
        title = $(this).attr('data-date');
        $(this).append('<span class="tooltiptext">'+ title +'</span>');
    },
    function(e){
        $('span', this).remove();
    }); 
</script>
</html>

Can anyone help me figure out what's wrong with the code?

Best regards, Elio Fernandes

Answer №1

It seems like a binding issue occurred because you tried to bind an event before the element was actually created in the DOM.

$(document).ready(function(){
        // Table Headers
        var headers = ["S", "M", "T", "W", "T", "F", "S"];  

        // Json Array
        var myData = [
            {"Date":"25/12/2016", "MonthName":"January","DataDiff":"7","MonthDays":"31"},
            {"Date":"29/01/2017", "MonthName":"February","DataDiff":"3","MonthDays":"28"},
            {"Date":"26/02/2017", "MonthName":"March","DataDiff":"3","MonthDays":"31"},
            {"Date":"26/03/2017", "MonthName":"April","DataDiff":"6","MonthDays":"30"}
        ];              

        // Create Table
        var cityTable = makeTable_HeadersOnly($('#tblContainer'), headers, "Planner", 6 );

        // Append data from Json array
        appendTableRowsJsonFile(cityTable, myData); 
    });

    // Make Table just with headers
    function makeTable_HeadersOnly(container, data, id, nrTimes) {
        var table = $('<table id=' + id + '/>');
        var row   = $('<thead/>');

        row.append($('<tr/>'));

        // First Column
        row.append($('<th/>').text(""));

        // Generates the columns
        for (i=1; i <= nrTimes; i++) {
            $.each(data, function(colIndex, c) { 
                row.append($("<th/>").text(c));
            });
        }
        table.append(row);

        // tbody
        row   = $('<tbody/>');
        table.append(row);

        return container.append(table);
    }

    // append table row from json file
    function appendTableRowsJsonFile($table, jdata) {
        var day = 1;
        var diff = 0;
        var daysMth = 0;
        var data = "";
        $.each(jdata, function(key, value){
            // Month
            let tr = $("<tr/>");    
            tr.append($("<td/>").text(value.MonthName));

            // Fill days
            diff = parseInt(value.DataDiff);
            daysMth = parseInt(value.MonthDays);
            for (i = 1; i <= 42; i++) { 
                if (i <= diff ){
                    tr.append($("<td/>").text(''));
                } else if (i <= diff + daysMth) {       
                    day = i - diff;
                    tr.append($('<td/ class="day" data-date="' + day +'" />').text(day));
                } else{
                    tr.append($("<td/>").text(''));
                }
            }
            $table.find('tbody').last().append(tr); 
        });
         bindhover();
    }
function bindhover() {
          // Tooltip - class 'day'
          $('.day').unbind();
          $('.day').bind({
              mouseenter: function (e) { 
                  title = $(this).attr('data-date');
                  $(this).append('<span class="tooltiptext">' + title + '</span>');
              },
              function (e) {
                  $('span', this).remove();
              }
          });
      }
.day {
        position: relative;
    }

    .day .tooltiptext {
        visibility: hidden;
        width: 120px;
        background-color: #555;
        color: #fff;
        text-align: center;
        border-radius: 6px;
        padding: 5px 0;
        position: absolute;
        z-index: 1;
        bottom: 125%;
        left: 50%;
        margin-left: -60px;
        opacity: 0;
        transition: opacity 1s;
    }

    .day .tooltiptext::after {
        content: "";
        position: absolute;
        top: 100%;
        left: 50%;
        margin-left: -5px;
        border-width: 5px;
        border-style: solid;
        border-color: #555 transparent transparent transparent;
    }

    .day:hover .tooltiptext {
        visibility: visible;
        opacity: 1;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><br/><br/></p>
    <div id="tblContainer"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The search feature using MySQL, PHP, and AJAX is malfunctioning

Hey everyone, I'm currently working on setting up a live search feature using PHP, MySQL, and AJAX. However, I seem to be encountering some issues in my implementation. My database is hosted on phpMyAdmin with the name "Info", and the specific table I ...

Combining an if-statement with an HTML button within a single function in JavaScript

I'm currently developing an HTML table that includes fields that must be filled, but I want to allow one of the fields to be optional. The structure of my code is as follows: name.html ... <table> <tr> <td>Number 1:</td& ...

Encountering an 'undefined' error when rendering data in Vue.js

For some reason, I am facing an issue with rendering data stored in a JSON object. It seems to work perfectly fine when written in plain JavaScript, but when I convert it to Vue, it fails to work. I even tried reverting back to an older commit to see if th ...

Testing React components with Jest by mocking unnecessary components

Consider a scenario where we have the Page component defined as: const Page = () => <> <Topbar /> <Drawer /> <Content /> </> When writing an integration test to check interactions within the Drawer and Con ...

Using Selenium WebDriver to handle Angular requests in Java

I am currently developing tests for an angular-based application and I find myself in need of assistance. The specific task at hand involves creating a mechanism that will wait until all pending requests within the application have been processed before pr ...

Error on node: The type of error encountered is TypeError. It appears to be related to req.query.acct_stmt_id not being

I encountered a puzzling issue where a particular route works flawlessly with an input array of size 10, but throws the error TypeError: req.query.acct_stmt_id.map is not a function when the input array size increases to 100. To run node, I am utilizing - ...

Passing the unique identifier of a record in NextJS to a function that triggers a modal display

I'm currently facing an issue with my NextJS component that displays a list of people. I have implemented a delete button which triggers a modal to confirm the deletion of a person, but I am struggling with passing the id of the person to be deleted. ...

Reviving jQuery Smooth Zoom Pan viewer following container resize

I am in the process of developing a responsive image viewer and have decided to incorporate the Smooth Zoom Pan plugin for enhanced pan/zoom functionality. Within my layout, I have two primary panels: the viewer container and a controls container that are ...

How to fix XmlHttpRequest PUT File Upload error when uploading files larger than 1MB

Uploading files to a server (in this case, S3) has been a smooth process for files under ~1MB. However, larger files tend to fail intermittently during the send operation. The issue does not seem to be related to security measures, CORS settings, or signin ...

When a child component sends props to the parent's useState in React, it may result in the return value being undefined

Is there a way to avoid getting 'undefined' when trying to pass props from a child component to the parent component's useState value? Child component const FilterSelect = props => { const [filterUser, setFilterUser] = useState('a ...

Tips for choosing the most current or upcoming item from a list using buttons

I am currently working on a small website project for one of my lessons. The task involves selecting items from a list and using two arrows to navigate to the item above or below the current selection. Here is an example: https://i.stack.imgur.com/FxZCN. ...

Encountered an issue accessing data during AJAX POST request using AJAX, MVC ASP.net, and .net framework 4.0

I am working with the following entity structure Entity AssetMgmt public class AssetMgmt : CommonPropertiesViewModel { public int DepartmentId { get; set; } public int TypeOfDevice { get; set; } public string DeviceStatus { get; set; } ...

Cheerio - Ensure accurate text retrieval for selectors that produce multiple results

Visit this link for more information https://i.stack.imgur.com/FfYeg.png I am trying to extract specific market data from the given webpage. Specifically, I need to retrieve "Sábado, 14 de Abril de 2018" and "16:00". Here is how I did it using Kotlin an ...

Troubleshooting: Javascript success callback not executing upon form submission

A snippet of my JavaScript looks like this: $(document).ready(function(){ $("#message").hide(); $("#please_wait_box").hide(); $("#updateinvoice").submit(function(e){ $("#message").hide(); ...

Upcoming JWT authentication module

I've been working on a simple application using next.js and integrating JWT for user authentication. My goal is to have a single navbar and layout that can dynamically adjust based on the authentication status. Below is my code: import React from "r ...

Is it advisable to hold off until the document.onload event occurs?

I'm working with a basic HTML file where I need to generate SVGs based on data retrieved through an AJAX call. Do I need to ensure the document is fully loaded by enclosing my code within a document.onload = function() { ... } block, or can I assume ...

Combine the elements to form a single text string with JavaScript

I initially used getElementById and it worked successfully. However, I now need to apply the same functionality to multiple div elements, so I switched to using classes. But now, when I use getElementsByClassName, it returns as undefined. (This function i ...

What are some ways to ensure that text can adapt to the size of a

I am looking to create dynamic text that adjusts based on the size of its parent container. As the parent container's size changes, I want the text to automatically adjust accordingly. Specifically, I want the text in a widget to resize when the widg ...

Adding Urls in a specific format using JavaScript: A Comprehensive Guide

I am looking to insert variable data in JavaScript in the given code within the URL $(document).on('change','.sort_rang',function(){ var url = "ajax_search.php"; //console.log($("#search_form").serialize()); var data = $("#sea ...

Troubleshooting problem with CSS borders in Microsoft Edge Browser

I am currently working on implementing the concept found at the following link: https://www.w3schools.com/howto/howto_js_tabs.asp, but with the additional feature of borders around the elements. However, I have encountered an issue specifically with Micro ...