Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to switch between row and column on button click

I am making a alternating div list in javascript. I have two requirements:

  • Alternate between two color for every even and odd indexed nodes
  • On every click, if currently divs are in a row, then switch to column, and vice versa.

I am able to meet first requirement, but stuck at second one (transition from row to column and column to row on every click). Also, I am not good at CSS so I am not able to do it using CSS.

const btn = document.querySelector('#divChanger');
const mainDiv = document.querySelector('.mainDiv');
for (let index = 0; index < 20; index++) {
  mainDiv.innerHTML += `<div class="myDiv"> Div ${index + 1} </div>`;
}
const selectedDiv = document.querySelectorAll('.myDiv');
var counter = 0;
selectedDiv.forEach(element => {
  if (counter++ % 2) {
    element.style.color = 'red';
  } else {
    element.style.color = 'blue';
  }
  element.style.fontSize = '14px';
});
btn.addEventListener('click', function() {
  selectedDiv.forEach(element => {
    element.style.color = element.style.color == 'red' ? 'blue' : 'red';
  });
});
<div class="mainDiv">
</div>

<div>
  <button id="divChanger">Change</button>
</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just set your element.style.float = element.style.float == 'left' ? 'none' : 'left'; inside your eventListener.

I’ve added maring as well, just for a better perspective

const btn = document.querySelector('#divChanger');
const mainDiv = document.querySelector('.mainDiv');
for (let index = 0; index < 20; index++) {
  mainDiv.innerHTML += `<div class="myDiv"> Div ${index + 1} </div>`;
}
const selectedDiv = document.querySelectorAll('.myDiv');
var counter = 0;
selectedDiv.forEach(element => {
  if (counter++ % 2) {
    element.style.color = 'red';
  } else {
    element.style.color = 'blue';
  }
  element.style.fontSize = '14px';
});
btn.addEventListener('click', function() {
  selectedDiv.forEach(element => {
    element.style.color = element.style.color == 'red' ? 'blue' : 'red';
 element.style.float = element.style.float == 'left' ? 'none' : 'left';
element.style.margin = "2,0";
  });
});
<div class="mainDiv">
</div>

<div>
  <button id="divChanger">Change</button>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading