M
M
Michael2019-01-26 00:46:14
JavaScript
Michael, 2019-01-26 00:46:14

How to optimize javascript code?

How to optimize javascript code?
It is necessary that when button 1 is pressed, the color of div 1 changes, when button 2 is pressed, the color of div 2 changes, and so on. At the same time, I can’t wrap them in a container, because on the site, these will be elements from different sections.
here is a simplified example :
https://codepen.io/mk3mk/pen/ZwQxMg?editors=0110
I want to put a variable instead of indexes, but I can't figure out how to do it
yes, and yet, this must be done in pure js

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-01-26
@mk3mk

You can link elements through additional attributes. For example .
UPD. Taken from the comments:

maybe you can somehow, so that, for example, the button with index 1 is pressed, it means that the div with index 1 changes there

This idea does not seem good to me - what if you later change the order of the buttons, but forget about the divs? In this case, the buttons will pull not their elements. But here you can see better. Choose:
One handler for all:
document.addEventListener('click', ({ target: el }) => {
  if (el.classList.contains('button')) {
    const index = [...document.querySelectorAll('.button')].indexOf(el);
    document.querySelectorAll('.div')[index].classList.toggle('red');
  }
});

Each button has its own handler:
const divs = document.querySelectorAll('.div');

document.querySelectorAll('.button').forEach((n, i) => {
  n.addEventListener('click', () => divs[i].classList.toggle('red'));
});

UPD. Taken from the comments:
only one div needs to be "changed" at a time

No problems:
document.addEventListener('click', ({ target: el }) => {
  if (el.classList.contains('button')) {
    const index = [...document.querySelectorAll('.button')].indexOf(el);
    document.querySelectorAll('.div').forEach(({ classList: cl }, i) => {
      cl.toggle('red', i === index && !cl.contains('red'));
    });
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question