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

Always listen to window screen changes

How do I make the code always respond to the changes in screen size?

I remember there is one globalEventHandler can do this but I’m not sure which one…

For example, the div#test-02 will always automatically adjust its width to 1/3 of the div#test-01. The problem is that as we use the developer tool (f12) to resize the window, the width of div#test-01 is keep changing but the code won’t respond to it anymore…Unless we reload the page…

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

const test01 = document.querySelector('#test-01');
const test02 = document.querySelector('#test-02');
const data = test01.getBoundingClientRect().width;

test02.style.width = `${data / 3}px`;
#test-01 {
  width: 100vw;
  height: 50vh;
  background-color: grey;
  display: flex;
  justify-content: center;
  align-items: center;
}

#test-02 {
  height: 100%;
  background-color: orange;
}
<div id="test-01">
  <div id="test-02"></div>
</div>

>Solution :

To listen for window screen changes, you can use

window.addEventListener("resize", callback)

This will listen for resize events on the window, and execute the callback function if such an event occurs. So you could put the code which resizes your elements relative to each other into the callback, so that it is executed on every window resize. (The callback will not be run on page load, so you would have to run your code outside of the event handler once too.)

The following code should work in your case:

const test01 = document.querySelector('#test-01');
const test02 = document.querySelector('#test-02');

function onResize() {
  const data = test01.getBoundingClientRect().width;
  test02.style.width = `${data / 3}px`;
}

window.addEventListener("resize", onResize, {passive: true})
onResize()
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