0

i did this code so I could mirror textareas:

<body>
<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>
    <br>
<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>

<script>
    var a = document.getElementsByClassName("caixa1");
    var b = document.getElementsByClassName("caixa2");
    a[0].oninput = function(e) {
      b[0].value = a[0].value;
    }
          b[0].oninput = function(e) {
      a[0].value = b[0].value;
    }
             a[1].oninput = function(e) {
      b[1].value = a[1].value;
    }
          b[1].oninput = function(e) {
      a[1].value = b[1].value;
    }       
</script>
</body>

But I need to repeat this 8 times. Is there any way I could create a variable that changes according to the class index of the current textarea?

1 Answers1

0

Iterate over each index of one of the collections, and access the same index on the other collection:

var a = document.getElementsByClassName("caixa1");
var b = document.getElementsByClassName("caixa2");
for (let i = 0; i < a.length; i++) {
  const t1 = a[i];
  const t2 = b[i];
  t1.oninput = () => t2.value = t1.value;
  t2.oninput = () => t1.value = t2.value;
}
<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>
<br>
<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>

An alternative would be to use event delegation on the container, and from the event target textarea, dynamically identify which is the linked adjacent textarea to assign a value to (either the next or previous sibling):

document.body.addEventListener('input', ({ target }) => {
  const other = target[target.matches('.caixa1') ? 'nextElementSibling' : 'previousElementSibling'];
  other.value = target.value;
});
<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>
    <br>
<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320