Home > Software design >  Change the Page layout when a button is clicked
Change the Page layout when a button is clicked

Time:08-22

I wanna change the layout of a page that has 3 columns

<div>
    <div >
      <div  >
        <div ></div>
        <div ></div>
        <div ></div>
      </div>
    </div>
  </div>

to 4 columns when a button is clicked.

<div>
    <div >
      <div  >
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
      </div>
    </div>
  </div>

right now I have no clue on how to doing this.

CodePudding user response:

There's a few ways this could be done depending on your data, however, here's one angle.

If you have both your 4 column & 3 column versions of the data loaded on the page (but one hidden with css). You could run something like this.

HTML

<div id="colsThree" >
  <div >
    <div  >
      <div ></div>
      <div ></div>
      <div ></div>
    </div>
  </div>
</div>

<div id="colsFour" >
  <div >
    <div  >
      <div ></div>
      <div ></div>
      <div ></div>
    </div>
  </div>
</div>

<button id="changeColumns">Click Me To Change Columns</button>

Javascript

const buttonEl = document.querySelector("#changeColumns");

buttonEl.addEventListener('click', () => {
  const outputEls = document.querySelectorAll('.displayArea')
  outputEls.forEach((outputEl) => {
    outputEl.toggle("show")
  })
});

CSS

.displayArea {
  display: none;
}

.displayArea.show {
  display: block;
}

CodePudding user response:

Use forEach and appendChild method.

const btn = document.querySelector('#btn')

btn.onclick = function() {
const targetClasses = document.querySelectorAll('.col-md-4')
targetClasses.forEach((tag, idx) => {
tag.className = 'col-md-3'

const lastIdx = targetClasses.length - 1
if (idx === lastIdx) {
const tag = document.createElement('div')
, row = document.querySelector('.row')
tag.className = 'col-md-3'
tag.innerText = '4'
row.appendChild(tag)
}
})

console.log(targetClasses)

return
}
<div>
<button id="btn">Click me</button>
    <div >
      <div  >
        <div >1</div>
        <div >2</div>
        <div >3</div>
      </div>
    </div>
  </div>

  • Related