M
M
Michael2019-01-30 23:55:28
JavaScript
Michael, 2019-01-30 23:55:28

How can the Javascript code be made more optimal?

there is an example of layout with javascript code. But the code is very long. And apparently not the best. How can it be optimized? to make it shorter, more readable, etc.
The gist of this example code is that there are 10 icons. When you click on the icon, a text block with information appears. And if you click on the second icon, the first block disappears and the second appears, and so on.
here is this example
https://codepen.io/mk3mk/pen/aXBeMb?editors=0010

Answer the question

In order to leave comments, you need to log in

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

Instead of manually switching the classes of each block, let's make a function that will take a block as a parameter and perform all the necessary actions:

function toggleClasses(block) {
  const info = block.querySelector('.infoWrapper');
  block.classList.toggle('marginBottom10');
  block.classList.toggle('marginBottom120');
  info.classList.toggle('displayNone');
  info.classList.toggle('displayBlock');
}

We will replace the connection of individual click handlers to each button with one delegated handler, and instead of manually iterating through all the blocks, we will simply look for an open one:
document.addEventListener('click', function(e) {
  const block = e.target.closest('.blockSvg');
  if (block) {
    const prevBlock = document.querySelector('.blockSvg.marginBottom120');
    if (prevBlock && prevBlock !== block) {
      toggleClasses(prevBlock);
    }

    toggleClasses(block);
  }
});

As a result, the amount of code was reduced by two orders of magnitude .
And of course, it is necessary to turn over, because here it is "correcting the position of the blocks" - some kind of disgrace.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question