I have 512 buttons, that when each is clicked, I want to update the state to either 1, 2, 3, or 4. Is there a way to create a function that will update the array when each button is clicked? As a sample, I am able to make 5 buttons, 5 different EventListeners,5 functions. Obviously, can’t do that when I have 512 buttons. How can I update my function to take in a button that is clicked?
<!DOCTYPE html>
<html>
<body>
<button id="b1"> 1</button>
<button id="b2"> 2</button>
<button id="b3"> 3</button>
<button id="b4"> 4</button>
<button id="b5"> 5</button>
<script>
var items = [0,0,0,0,0]
button1 = document.querySelector("#b1");
button2 = document.querySelector("#b2");
button3 = document.querySelector("#b3");
button4 = document.querySelector("#b4");
button5 = document.querySelector("#b5");
button1.addEventListener("click",updateArray1);
button2.addEventListener("click",updateArray2);
button3.addEventListener("click",updateArray3);
button4.addEventListener("click",updateArray4);
button5.addEventListener("click",updateArray5);
function updateArray1() {items[0]=1; console.log(items)}
function updateArray2() {items[1]=1; console.log(items)}
function updateArray3() {items[2]=1; console.log(items)}
function updateArray4() {items[3]=1; console.log(items)}
function updateArray5() {items[4]=1; console.log(items)}
</script>
</body>
I am able to update the array by writing a function. How can I loop over the event listeners?
3
Answers
You can use querySelectorAll to get all buttons, and then you can use for of Loop to bind event Listener to all buttons. Lastly you can use event.target inside the event listener callback function to get the target button. Here is a sample code:-
I’m not sure what are you trying to do by adding 512 buttons but I hope this helps you