Populating an array during an event and then utilizing it outside of the event function handler

I have a challenge where I need to populate an array with values from various buttons whenever they are clicked. The goal is to then access this array outside of the event handler function. Although I have attempted a solution, I am struggling to access the array as intended.

Below is the relevant HTML code:

<button value="5"> button </button>
<div> The value is: <span id="res"></span></div>

And here is the associated script:

var n = [];
var val;
var ret;

function add(arr,val) {
arr.push(val); 
return val;
} 
document.body.addEventListener("click", function(event) {
    if (event.target.nodeName == "BUTTON") {
        val = event.target.value;
        ret = add(n, val); 
        console.log(n);      //testing
        console.log(ret);
    } 
 console.log(ret);    
});

//attempts to access the array from here
console.log(n);    
console.log(ret); 

document.getElementById("res").innerHTML = ret;  //currently undefined

I understand that the issue lies in the fact that everything is contained within the event handler function. However, I am unsure how to achieve the desired outcome.

Does anyone have any suggestions?

Answer №1

It's imperative to execute the desired action within the callback function, not beforehand. This is because the event handler's code doesn't run until the event actually takes place. Merely declaring a variable won't alter the sequence of operations.
Therefore, ensure to include

document.getElementById("res").innerHTML = ret;

inside the event handler function.

Here's the updated (and simplified) code snippet:

var n = [];

document.body.addEventListener("click", function(event) {
    if (event.target.nodeName == "BUTTON") {
        var val = event.target.value;
        n.push(val);
        console.log(n);      //these console.log are tests
        console.log(ret);
        document.getElementById("res").innerHTML = val;
    }
});

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

Exploring Interactive Designs with Vue.js

In order to dynamically construct a series of CSS style classes based on the toolName property in the JSON data using Vue 2, I tried to use a computed property to bind them to the existing span with a class of panel-icon. However, when attempting to save t ...

Establishing a Geolocation Object in HTML5

My HTML5 app relies on Geolocation. In cases where the user denies permission for geolocation, I want to pass a default position object (latitude:0, longitude:0) to ensure the app can still function. I understand how to detect permission denial, but I&apo ...

Using the setTimeout function with asynchronous tasks

I have a situation where I need to introduce a 5000ms delay before firing an asynchronous function. To accomplish this, I attempted to utilize the setTimeout() method. This async function is called within a loop that runs multiple times, and each time it i ...

Implementing CORS in ReactJs: A Step-by-Step Guide

When working with React.js, I often use this fetchData config: fetchData = () => { fetch("http://localhost:8000/batch_predict", { method: "POST", headers: { 'Accept': 'application/json, text/plain, */*&apo ...

Generate a multi-dimensional array using an array of specified keys

I'm having some trouble creating a nested array using an array of keys and assigning a value to the last nested item. For instance, if $value = 4; and $keys = ['a', 'b', 'c']; The desired output should be: [ 'a& ...

Encountering an error message stating "Buffer is not defined" while working with gray-matter

Encountering an issue when trying to utilize gray-matter in Angular 9, the error message displayed is: ReferenceError: Buffer is not defined at Object.push../node_modules/gray-matter/lib/utils.js.exports.toBuffer (utils.js:32) at push../node_modul ...

What is the method for establishing a callback for call status using the Twilio Voice JavaScript SDK?

Currently, I am in the process of utilizing the Twilio Programmable Voice JavaScript SDK to initiate an outbound call with a statusCallback and statusCallbackEvent in order to update another system once the call is finished. Below is the snippet of my cod ...

How can you use Knex to order the results for each WHERE clause in a SELECT query?

When querying a database using knex, the desired results should be ordered in a specific manner. The current code provides the required results but lacks the expected order. knex("FRUITTBL") .select("FruitTag", "FruitName", ...

Innovative approach to accessing structures in C

I have a unique project that requires the development of a C program for specialized software utilized within my company. My goal is to optimize the program for efficiency, but I have encountered an unusual challenge with how the software handles the signa ...

Having trouble with the input range slider on Chrome? No worries, it's working perfectly fine

I'm currently facing an issue with an input range slider that controls the position of an audio track. It seems to work perfectly in Firefox, but in Chrome, the slider gets stuck and doesn't move when dragged. There is a function in place that up ...

Experiencing difficulties connecting with aspx while using Ext JS 4.2

Currently, I am facing an issue with making a call to an ASPX URL as the return keeps coming back as a failure. I have successfully used this URL in previous programming projects, but this is my first time utilizing it with Ext JS. Despite researching dif ...

Enhancing the functionality of a bootstrap button with the addition of an

My goal is to have a button that opens a URL in a new tab. I've managed to achieve this using window.location.href, but it doesn't open the URL in a new tab. The code I'm working with is written in jQuery and Javascript, and it's part ...

React & Material UI: Unleashing the Power of Chained Arrow Functions

I stumbled upon this code snippet while browsing through the Material UI docs on Accordion. Despite spending hours trying to understand it, I'm still struggling to grasp its functionality: export default function CustomizedAccordions() { const [expa ...

Substitute a JSONP API call using $.ajax() with a direct server-to-server API call

My javascript application utilizes an ajax function that has the following structure: $.ajax({ url: apiURL, dataType: 'jsonp', success: function(data) { if (data.ok) { //perform actions }}}); Everything was working perfectly until I ...

Unable to convert date data for display on D3 line graph

I am attempting to replicate a line graph similar to the one in the following fiddle link: http://jsfiddle.net/wRDXt/2/ In the example, the date is used as new Date(2013, 17, 1). The JSON data I have is structured as shown below, [{ "_id": "bb68d8a2 ...

Guide on linking draggable elements

Currently, I have a set of div elements that I am able to clone and drag and drop into a specific area. Now, I am looking for a way to connect these divs with lines so that when I move the divs, the lines will also move accordingly. It's similar to cr ...

The functionality of jQuery touch events on iOS devices is not functioning properly

I'm encountering issues with jQuery touch events on iOS devices. Here is my current script: $(document).ready(function(){ var iX = 0,iY = 0,fX = 0,fY = 0; document.addEventListener('touchstart', function(e) { ...

What is the best method for effectively eliminating duplicate objects with the same value from an array?

Let's say we have a collection of jqlite objects, and using the angular.equals function, we can determine if they are equal. How can we utilize this function to eliminate duplicate items from an array of jQlite objects? This is my attempted solution: ...

Why isn't my Bootstrap dropdown displaying any options?

I am new to web development and attempting to create a button that triggers a dropdown menu when clicked. I have tried the following code, but for some reason, the dropdown is not working correctly. Can anyone help me identify the issue or correct my code? ...

Having trouble establishing a connection between MongoDB Atlas, NodeJS, and Mongodb

Encountering an issue while attempting to establish a connection with MongoDB. The error seems to be related to the 'connect' keyword itself. I am unsure of what the exact problem is. The error message displayed is as follows: mongodb.connect( ...