Embedding JavaScript information into a cell of an HTML table

I am currently working on creating a pop-up box that, when triggered (with a delay), will showcase a counter displaying the number of clicks along with the dates of each click!

I would like to present this information in a structured table format within a cell, similar to the following example:

Clicks         Time

 1            Thursday 4, 2018
 2            Monday 3, 2018

Below is the snippet of my HTML code implementation:

function DisplayMessage() {
  document.getElementById('myText').innerHTML = 'Hey <strong>Thanks!</strong>';
}

var clickCounter = 1;
var popupElement = document.getElementById("popup");
var inputField = document.getElementById("popup-delay");
var displayButton = document.getElementById("popup-show");
var closeButton = document.getElementById("popup-close");

displayButton.addEventListener("click", function onClickToShow() {

  var userInput = parseInt(inputField.value, 10);

  if (isNaN(userInput)) {
    alert("NaN (Not A Number) !");
  }
  else {

    var timeDelay = userInput * 1000;

    displayButton.removeEventListener("click", onClickToShow);

    document.getElementById("num1").innerHTML = clickCounter;
    clickCounter = clickCounter + 1;
    document.getElementById("num4").innerHTML += "<span>" + Date() + "</span>";
    
    setTimeout(function() {

      popupElement.style.display = "block";

      closeButton.addEventListener("click", function onCloseClicked() {
       
        closeButton.removeEventListener("click", onCloseClicked);

        displayButton.addEventListener("click", onClickToShow);

        popupElement.style.display = "none";
      });
    }, timeDelay);
  }
});
#popup {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: yellow;
  padding: 1em;
}

#thecounter {
  float: right;
  background-color: rebeccapurple;
  padding-top: 50px;
  padding-bottom: 50px;
  width: 10%;
  margin-right: 10px;
  font-size: 30px;
  color: white;
  text-align: center;
}

#thetime {
  float: right;
  background-color: rosybrown;
  padding-top: 50px;
  padding-bottom: 50px;
  width: 10%;
  font-size: 30px;
  color: white;
  text-align: center;
}

#num4 span {
  font-size: 20px;
  display: block;
  margin-bottom: 4px;
  padding: 4px;
}
Delay: <input type="text" id="popup-delay" />  <button type="button" id="popup-show">Show</button>
<div id="popup">
  <p>I am a popup :-)</p>
  <button type="button" id="popup-close">Close</button>
</div>
<div id="container">
  <div id="thecounter">
    <p id="num2">clicks </p>
    <p id="num1">0 </p>
  </div>
  <div id="thetime">
    <p id="num3">time </p>
    <p id="num4"> </p>
  </div>
</div>

Answer №1

One issue arises when attempting to access elements by id before the DOM is fully rendered, resulting in a null value being returned consistently. To address this problem, modify the event listener of the button accordingly:

 function onShowClick () {

var popup = document.getElementById("popup");
var input = document.getElementById("popup-delay");
var showButton = document.getElementById("popup-show");
var closeButton = document.getElementById("popup-close");
  // Obtain user input and convert it into a number
  var value = parseInt(input.value, 10);
  // Check if the input is not a number
  if (isNaN(value)) {
    // Notify the user about invalid input
    alert("NaN (Not A Number) !");
  }
  // Handle valid inputs
  else {
    // Convert milliseconds to seconds
    var delay = value * 1000;
    // Disable click listener for the "Show" button
    showButton.removeEventListener("click", onShowClick);
    // Begin countdown to display the popup
   //      document.getElementById("num1").innerHTML= counter1;
      counter1= counter1+1; 
      let currDate = Date();
 //   document.getElementById("num4").innerHTML += "<span>" + currDate + "</span>"; 
 // Add a new row to the table
      let table = document.getElementById("table");
      var tr = document.createElement('tr');
      var tdCounter = document.createElement('td');
       tdCounter.appendChild(document.createTextNode(counter1))
      tr.appendChild(tdCounter)
      var tdTime = document.createElement('td');
      tdTime.appendChild(document.createTextNode(currDate))
      tr.appendChild(tdTime)

       table.appendChild(tr)

    setTimeout(function () {
      // Display the popup after the designated delay
      popup.style.display = "block";
      // Enable click listener for the "Close" button
      closeButton.addEventListener("click", function onCloseClick () {
        // Disable click listener for the "Close" button
        closeButton.removeEventListener("click", onCloseClick);
        // Re-enable click listener for the "Show" button
        showButton.addEventListener("click", onShowClick);
        // Hide the popup
        popup.style.display = "none";



      });
    }, delay);
  }
}

To invoke this function on a button's onclick event in the HTML code, implement it as shown below:

    <body>
Delay: <input type="text" id="popup-delay" />
<button type="button" onclick="onShowClick()" id="popup-show">Show</button>
<div id="popup">
  <p>I am a popup :-)</p>
  <button type="button" id="popup-close">Close</button>
</div>


<div id="container">
<table id="table">
</table>    

</div>
</body>

The expected output will resemble the following:

Main Page Pop up Page

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

Retrieve HTML content from Vuetify components without displaying it on the webpage

I have a project where I need to retrieve the HTML code from various Vuetify components. Instead of just as a HTML string, I actually need it as a DOM element that can be easily added to the body. This is necessary for me to be able to utilize these compon ...

What is the best way to combine an array of objects into a single object in typescript?

Looking for some help with converting an array of objects into a single object using TypeScript. Here's the structure of the array: myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: ' ...

Styling Circles with CSS

HTML: <ul class="list_header"> <li><a href="#">06 december 2013</a></li> <li><a href="#">item2</a></li> <li><a href="#">item3</a></li> ...

How to position radio buttons in line with labels containing inline inputs using Vue and Bootstrap

Currently, I am facing an issue with my form containing a radio button group where one of the radio button labels includes another numerical input. The layout is not aligned correctly, and I am struggling to adjust the spacing using CSS. I am unable to gr ...

Exploring the world of jQuery animation and background colors with Animate()

I'm currently attempting to implement a basic pulse effect by utilizing JQuery to modify the background color. However, I am facing issues with animating the backgroundColor property. function show_user(dnid) { /* dnid represents the HTML ID of a ...

Adding a question mark at the top of the content in a txt file using node.js's

When I use the fs.readFile() function to retrieve data from a .txt file, I notice that the content begins with "?Alex libman". Here is the code snippet: fs.readFile(__dirname+"/txts/generate/titles0.txt", "utf-8", function (ex, titles) { var titlesArr = ...

What is the best way to store data retrieved from an asynchronous database callback in Nodejs with express?

After querying my sqlite3 database to verify user details, I encounter an issue when trying to store the retrieved data in a session variable or global instance. Despite being able to access the data within the callback function, it becomes undefined once ...

What is the process for designing a button with a circular element connected to its left edge?

I am currently working on creating a unique button design using a combination of HTML and CSS. The button is rectangular on three sides, with a circular section attached to the right side where the buttons border seamlessly wraps around it. Below is an im ...

Stylish navigation bars with CSS and Jquery for seamless browsing experience

I am attempting to create a simplistic horizontal list menu similar to the one displayed in this example. I have copied the list and CSS to jsFiddle (New Example Update), but it does not function as desired. I have searched for similar examples to guide me ...

What is preventing my JavaScript variable from being defined outside of this function?

I am currently working on a script where I need to retrieve the dimensions of an image for later use. While directly selecting the img element with jQuery is convenient and efficient, it does not work smoothly in webkit browsers as the image may not be loa ...

Adding a SpotLight to Camera in ThreeJS: A Step-by-Step Guide

Trying to add a flashlight effect using Three.js r105 I'm attempting to attach a SpotLight to the camera to achieve a "Flashlight" effect. However, once I connect the SpotLight to my Camera, the light seems to completely stop working. What could be t ...

Filter an array using an algorithm inspired by Binary Search Trees

I am facing a challenge with a sorted array of dates, here is an example: let arr = ['2019-03-12', '2019-02-11', '2019-02-09', '2018-06-09', '2018-01-24', ..] The arr has a length of 100,000, and I need t ...

When incorporating a script in a Gatsby site, remember to load it only once on the initial

I am experiencing an issue with my custom script not loading on every page navigation. I have created a js file called custom.js in the static folder, but it seems to only load the script once upon the initial page load. This is the content of my custom.j ...

A guide on iterating and accessing Vue data in a loop

I am looking to iterate through my code in order to extract the value of each form input. This is to ultimately display a total score and severity score based on the user's inputs. The total score will count the number of symptoms present (0-3), while ...

How can I make a Bootstrap 4 modal autoplay an iframe on page load?

My website features a full-screen background video that plays upon loading, and I want the same video to play when a user clicks the play button to open a modal. However, my issue is that the modal video (iframe) starts playing in the background as soon ...

Implement Conditional Enabling of Forms in JavaScript or jQuery to Support Single Form Usage

I currently have four forms labeled as form-1, form-2, form-3, and form-4, along with three buttons named Button-1, Button-2, and Button-3. Upon loading the first JSP page, it displays form elements on the screen. My query pertains to clicking on button- ...

The functionality of an external Javascript library fails to operate properly once the website is deployed to a hosting

Encountering a peculiar bug with my website at . The website is supposed to load both the JQuery and EasyUI libraries. JQuery is loading correctly as a function to print out "ready" when the page loads. The issue arises when trying to drag products onto th ...

Firefox causing line-height problem

Having an issue with styling a search button in Firefox. The input submit is created using an iconic font, white background, and border-radius as shown below: display: block; width: 60px; height: 60px; line-height: 60px !important; padding: 0; background: ...

The React application is showing an empty page without any visible errors during the compilation process

I'm having trouble with my React app - it compiles without errors but only shows a blank page. Can someone help me figure out what's wrong with my code? I'm new to React and could use some guidance. index.js import React from 'react&ap ...

passport not initializing session with requests

I am currently utilizing passportJS for managing login and persistent sessions on the server backend. While everything functions properly when sending requests from the server frontend (a webpage that I didn't create and lack sufficient knowledge to ...