0

I am adding some JS to an HTML, and I have a fragment of code similar to this:

<script>
function ButtonAction(index){
    alert("My index is: "+index);
    if(window_big){
        // Use index to do something
    }
    else{
        // Use index to do something else
    }
}
function WindowResize(){
    if(window.innerWidth > 1200){
        window_big = true;
    }
    else{
        window_big = false;
    }
}

var window_big;
if(window.innerWidth > 1200){
    window_big = true;
}
else{
    window_big = false;
}

buttons = document.getElementsByClassName('MyButtons')
var i;
for (i = 0; i < buttons.length; i++) {
    alert(i);
    buttons[i].addEventListener("click",function(){ButtonAction(i);},false);
}
window.onresize = WindowResize;
</script>

The idea can be summarized like this:

  • There is a series of buttons in the page, stored in buttons[].
  • If the window is bigger than a certain size, those buttons should do one action, and if not, do another one.
  • To do said actions, I need the button[x].id. In fact, the initial intention was to set the listener to:
buttons[i].addEventListener("click",function(){ButtonAction(i);},false);

The problem is that I cannot retrieve the id, because the argument passed in the event listener seems to be always the last value i was set to. May I ask for some help, please?

sergi.e
  • 1
  • 1
  • 1
    `for ( let i = 0; ` – Andreas Oct 14 '20 at 13:27
  • Long version of @Andreas's comment : The problem with your global `var i` is the following : say you add 10 events listeners; at this moment, after the loop, `i==10`. Then you click any button; `i` will always be equal to 10, no matter what you do. In order to "embed" each value of `i` inside each event listener, you need a closure, which is quite complicated. Fortunately, since ES6 we can use `let` instead of `var`, which creates a very handy local-scoped variable for each loop. The solution is therefore `for( let i=0; ....) ` – Jeremy Thille Oct 14 '20 at 13:35
  • And an even "longer" explanation can be found in the dupe targets ;) – Andreas Oct 14 '20 at 13:39

0 Answers0