There is such a code:

for (var i = 0; i <= some.length; i++) { block1[i].onmouseenter = function() { block2[i].classList.toggle('active_game'); } } 

block2 does not get i

Here is what I planned:

 block1[0].onmouseenter = function() { block2[0].classList.toggle('active_game'); } block1[1].onmouseenter = function() { block2[1].classList.toggle('active_game'); } 

Tell me, please, how can I solve this problem? Preferably on native js.

Reported as a duplicate at Grundy. javascript Jan 15 at 11:48 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • html code in the studio - Excess Suslik
  • Replace var with let . - Stepan Kasyanenko

1 answer 1

All handlers in your code refer to one variable i . You can replace var with let or try this option:

 for (var i = 0; i <= some.length; i++) { createHandler(i); } function createHandler(id) { block1[id].onmouseenter = function(){ block2[id].classList.toggle('active_game'); } } 
  • Replaced in for with let and it worked. Thank you more - Vlad Karablin