Home > Enterprise >  How to change height of box together with its width?
How to change height of box together with its width?

Time:01-01

I want to publish on my page section with articles in rows if form of boxes. I use bootstrap grid system to make it responsive. I set width of boxes to be 100%. And I want height to be as the same as width. For this I wrote an javascript code to execute this task:

document.addEventListener("DOMContentLoaded", function(event) { 
    let width = document.querySelectorAll(".post-boxes .box");
    width.forEach(item =>{
    item.style.height = `${item.offsetWidth}px`
    });
  });

But the problem is it works only when DOM is loaded for the first time, and if screen size is change, height remain the same.

This is my photo of boxes:

IMG

CodePudding user response:

DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

If you want to recalculate the height then add event handler for onresize

window.addEventListener('resize', <your-handler>);

CodePudding user response:

One solution is to run the function again when the screen is resized. You can use the resize event for this. Here is an example:

function box(){
    let width = document.querySelectorAll(".post-boxes .box");
    width.forEach(item =>{
    item.style.height = `${item.offsetWidth}px` })
}

document.addEventListener("DOMContentLoaded", () => box() );
window.addEventListener("resize", () => box() );
  • Related