Answer the question
In order to leave comments, you need to log in
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
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');
}
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);
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question