frankakn_7 frankakn_7 - 3 months ago 12
CSS Question

How to loop through Buttons infinite amount of times

I want to loop through the buttons 30 times a second i have an array in which i have listed the buttons

function Btn_check(){
for(var i in buttons){
var buttons_name = [];
buttons_name[i] = buttons[i].name+'_Btn';
document.getElementById(buttons_name[i]).onclick = function() {
//do something here
}
}
}

setInterval(Btn_check(), 1000/30);


in my HTML i just have a list of buttons like so

<a href="#" id="1_Btn" class="button">1</a>
<a href="#" id="2_Btn" class="button">2</a>
<a href="#" id="3_Btn" class="button">3</a>
//etc...


always when i click on a button it thinks i clicked the last button on the page

ant ant
Answer

Not sure exactly what you are trying to do. It looks like you are looping through object properties of 'buttons' - which is unclear what buttons is supposed to be. And not sure why you need a button_names array when, if fetched properly, buttons should provide you with the node and its properties - assuming that buttons is all elements with classname buttons.

So here's my best effort at what you're trying to accomplish:

var buttons = document.querySelectorAll(".button");
function Btn_check(){
    for(var i=0; i<buttons.length; i++) {
      buttons[i].onclick = (function(n) {
        return function() {
          alert(buttons[n].getAttribute("id"));
        }
      })(i);

    }
}

setInterval(Btn_check(), 1000/30);

A fiddle: https://jsfiddle.net/bcyab7z4/

Comments