Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

92
Views
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>

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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>

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!