How can you activate events on elements that are created later in Javascript?

I have developed my version of the Windows calculator, but I am facing a challenge with the "memory tab."

My task is to create click events for the three buttons - MC, M+, M- located at the top right corner of the screen:

https://i.sstatic.net/Gd8CC.jpg

The issue is that these buttons (along with other elements) are generated every time I click "MS" on the main calculator situated on the left side of the screen, above the main buttons.

function addMemoryValue(){
  const uls = document.createElement("ul");
  const lis = document.createElement("li");
  const h2s = document.createElement("h2");
  h2s.textContent = Number(display.textContent);
  const h3s = document.createElement("h3");

  uls.appendChild(lis);
  lis.appendChild(h2s);
  h2s.appendChild(h3s);

  let valueBtn = ["MC", "M+", "M-"];

  valueBtn.forEach((element) => {
  const memoryBtn = document.createElement("button");
  memoryBtn.setAttribute("value", element);
  memoryBtn.textContent = element;
  const memorySpn = document.createElement("span");
  memorySpn.appendChild(memoryBtn);
  memoryBtn.classList.add("btnsave");
  h3s.appendChild(memorySpn);

  const buttonTest = document.getElementsByClassName("btnsave");
  console.log(buttonTest.textContent);
  })

I aim to iterate through these buttons and set up if statements based on their textContent, but I am unsure how to target the buttons since they are not yet present.

If, for example, I attempt the following:

const buttonTest = document.getElementsByClassName("btnsave");
console.log(buttonTest.textContent);

I receive "undefined," regardless of whether console.log is inside or outside the function.

Answer №1

One way to add click event handlers directly to buttons is by creating them like this:

var clickHandler = function() {
    console.log("button clicked");
};

var button = document.createElement("button");
button.textContent = "test";
button.addEventListener("click", clickHandler);

document.getElementById("container").appendChild(button);
<div id="container">

</div>

Another way to handle events:

This code snippet will generate three buttons with different event handlers for each one.

var createButton = function(title, clickHandler) {
    var button = document.createElement("button");
    button.textContent = title;
    button.addEventListener("click", clickHandler);

    return button;
};

var removeButtons = function() {
    var container = document.getElementById('container');
    
    while (container.firstChild) {
      container.removeChild(container.lastChild);
    }
};

var createButtons = function() {
    removeButtons();
    
    var container = document.getElementById('container');
    
    container.appendChild(createButton("button 1", () => console.log("button 1 clicked")));
    container.appendChild(createButton("button 2", () => console.log("button 2 clicked")));
    container.appendChild(createButton("button 3", () => console.log("button 3 clicked")));
};

document.getElementById('create').addEventListener("click", createButtons);
document.getElementById('remove').addEventListener("click", removeButtons);
#container {
  border: 1px dashed teal;
  min-height: 1em;
}
<button id="create">generate buttons</button>
<button id="remove">remove buttons</button>

<div id="container"></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

Creating a dynamic pulse effect using jQuery to manipulate CSS box-shadow

My goal is to create a pulsating effect using CSS box-shadow through jQuery. Despite my best efforts, the code I attempted failed to produce the desired smooth pulse effect with box-shadow. The code snippet I experimented with: <div class="one"> &l ...

Swap image in div upon hovering over a list of links in another div

I'm in the process of designing a webpage that features a header and footer fixed to the top and bottom of the browser window, with adaptable content in between. To structure the inner content, I've opted for a flexbox wrapper containing a list o ...

Is it possible for $templateCache to preload images?

Is there a way to preload images in Angular without using a spinner after the controller is initialized? I've heard about caching templates with $templateCache. Can this be used to also preload images when the template contains <img> tags or sty ...

How to Determine if Your Chrome Packaged App is Operating in Kiosk Mode

I'm in the process of developing an application that is able to function both in kiosk mode and regular mode (such as opening from a Chrome browser). However, I need certain features to be restricted to kiosk mode only. How can I determine if the appl ...

Add a dynamic Angular component (HTML) to the TinyMCE editor by clicking a button

I am attempting to incorporate components with a table, header, and footer into the editor upon button click. However, I am facing an issue where it is not rendering as expected. Below is what I have attempted so far and what I am seeking. Successful Atte ...

What is the best approach for looping through an array fetched using Ajax in Vue?

<div class="recipe-ingredients__container__functions paddings"> <h5>Functions_</h5> <div class="foo" v-for="f in content.functions"></div> </div> When the HTML is rendered by Vue, the Ajax call is still in progr ...

I am interested in creating a ranking system in JavaScript using JSON data based on points

I have a desire to create the following: var users = {jhon: {name: 'jhon', points: 30}, markus:{name: 'Markus', points: 20}}; // I want it to return like this 1. Jhon with number of points: 30 // 2. Markus with number of points: 20 ...

Disabling a button does not automatically shift the focus to the next element in the tab order

Is there a way to limit the number of times a button can be clicked using jQuery? For example, I want a button that can only be clicked three times before disabling itself automatically. test.html <div class="main"> <input class="one" type="t ...

When removing a class from a group of elements in JavaScript, it seems to only erase approximately fifty percent of the

I've been working on a Word Puzzle algorithm that involves displaying a set of words on a grid for users to solve. They can either attempt to solve the puzzle themselves or click a "solve" button, triggering a function to visually solve the Word Puzzl ...

Transform your .obj files into .glb files effortlessly with npm and Laravel

I've hit a roadblock for 2 days now and can't seem to find a solution. Could someone lend me a hand with this? Query: What's the best way to convert a .obj file to .glb? I attempted using obj2gltf npm package but integrating it with Larav ...

Joi validation that focuses on required array elements while disregarding nested keys

Why is my Joi array required validation not detecting an empty array? I have an array called userData that contains objects with keys dateMilli and value. Despite adding required validations everywhere, passing an empty array [] for userData does not resul ...

Simulate internationalization for vue using jest

Currently, I am working on setting up jest unit tests for a Vue project within a complex custom monorepo. I am facing an issue with i18n, which I use for translation management in my application. The problem arises with the following code snippet for init ...

jQuery/MVC3 script not triggering onclick event after initial execution

Hey there, I'm having an issue with a function that is triggered when clicking on an image. It seems to only be called once even though I expect it to be called multiple times. Here's the JavaScript code, combined with a bit of razor syntax, tha ...

Tips for utilizing multiple ngFor directives for property binding within a single directive

After implementing the ng-drag and drop npm module with the draggable directive, I encountered an issue while trying to display a list of items from a 2D array using li elements. Since multiple ngFor's are not allowed in Angular, I needed to come up w ...

Customize the header color of open panels in Bootstrap 4

Within my HTML templates, which are based on Bootstrap 4.3.1, I successfully altered the behavior of accordions thanks to support from the Stack Overflow community. Now, only one panel can be open at a time, automatically closing any previously opened pane ...

When the window size is reduced, the image continues into the next div

I need to create a page that displays text alongside an image. However, when the window size is minimized, the image overlaps with the text. Here is how it looks: https://i.sstatic.net/CBMh8.png To fix this issue, I am using the following HTML code: ...

What is the best way to include a new css class in the surrounding tag when using Sitecore's MVC HtmlHelper for fields?

My goal is to display the content of @Html.Sitecore().Field(TPage.Headline) within an <h1 class="page-heading"> tag only if it contains a value. I do not want to render the surrounding <h1 class="page-heading"> tag when the field is empty. Alt ...

Personalized input element featuring integrated chips and accompanying text

I am in the process of designing a unique custom input element with dual functionality. It allows users to input text It enables users to embed or remove chips within the text by selecting an option from a dropdown menu My current development stack inclu ...

The code runs perfectly on CodePen, but it's not functioning properly on my website

After successfully resolving an issue on Codepen, I encountered a problem when transferring the JavaScript/JQuery code to my website. It seems that none of the JavaScript functionalities are working properly. Here is the link to the functional Codepen: htt ...

The onChange event seems to be failing to activate during a jQuery / Ajax form submission

Differences in Form Submission Methods The onChange event functions correctly with the traditional Type and Action method in both Firefox and Chrome. <form name="frmname" action="./add_p.php" method="POST"> <div> <select name=" ...