0

So bascially I am trying to have a div in flexbox that contains other divs and I want to be able to change flex-direction by clicking two buttons above it.

<body>
 <div>
  <button class="button-1">Display Column</button>
  <button class="button-2">Display Row</button>
 </div>
 <div class="main">
  <div class="container-1">One</div>
  <div class="container-2">Two</div>
  <div class="container-3">Three</div>
 </div>
 <style>
  .main{
  display: flex;
  }
 </style>
</body>

I am new to JS and I cant find anything that would work. Any Help?

2 Answers2

0
  • Use data-* to assign a custom attribute with value
  • Use JS's dataset to retrieve the data-* value
  • Use type="button" on action elements buttons that are not of type submit
  • Don't use unique classNames. Class should be common, IDs should be unique
  • Never use onclick handlers (as wrongly suggested in other answers) , unless you're creating brand new Elements from in-memory. Use addEventListener() instead:

// DOM utility functions:

const ELS = (sel, par) => (par || document).querySelectorAll(sel);
const EL = (sel, par) => (par || document).querySelector(sel);

// Task:

const changeDirection = (evt)  => {
  const direction = evt.currentTarget.dataset.direction;
  EL(".main").style.flexDirection = direction;
};

ELS("[data-direction]").forEach(EL_btn => EL_btn.addEventListener("click", changeDirection));
.main {
  display: flex;
}
<div>
  <button type="button" data-direction="column">Display Column</button>
  <button type="button" data-direction="row">Display Row</button>
</div>
<div class="main">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
-1

Using addEventListener() function:

let mainDiv = document.querySelector('.main');

document.querySelector('.button-1').addEventListener('click', () => {
  mainDiv.style.flexDirection = 'column';
});

document.querySelector('.button-2').addEventListener('click', () => {
  mainDiv.style.flexDirection = 'row';
});
.main {
  display: flex;
 }
<div>
  <button class="button-1">Display Column</button>
  <button class="button-2">Display Row</button>
</div>
<div class="main">
  <div class="container-1">One</div>
  <div class="container-2">Two</div>
  <div class="container-3">Three</div>
</div>
Samball
  • 623
  • 7
  • 22
  • This works very well. But I have another problem. I need to change css properties of the subDivs in that flexbox. Is there any way to change class of those subDivs? – Klob0ucek Mar 15 '22 at 11:23
  • You could select them like this: `let containers = document.querySelectorAll('.main div');` that returns an array that you can loop over and change the class, so: `for (let i = 0; i < containers.length; i++) { containers[i].classList.add('name_of_class') }`. – Samball Mar 15 '22 at 12:08
  • Thank you stranger! Problem solved. – Klob0ucek Mar 15 '22 at 19:24