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?