Tuesday, 17 May 2022

To merge window resizing and loading the page events into one function

I have a local html page that serves me a chaet sheet about how width, max-width and min-width work. It dynamically (that is, you are welcome to resize that page) reports you the widths of the body element and an inner div. It also changes the div's background color.

const div = document.querySelector('div');
const body = document.querySelector('body');

const outputDivWidth = document.querySelector('#outputDivWidth');
const outputBodyWidth = document.querySelector('#outputBodyWidth');

function reportWidths() {
  const divWidth = div.offsetWidth;
  const bodyWidth = body.offsetWidth;

  outputDivWidth.textContent = divWidth;
  outputBodyWidth.textContent = bodyWidth;

  if (divWidth >= 500) {
    div.style.backgroundColor = 'rgb(0% 100% 0% / 10%)';
  } else if (divWidth <= 300) {
    div.style.backgroundColor = 'rgb(100% 0% 0% / 10%)';
  } else {
    div.style.backgroundColor = 'rgb(100% 100% 0% / 10%)';
  }
}

reportWidths();
window.addEventListener('resize', () => {
  reportWidths();
});
body {
  outline: blue solid 1px;
}

div {
  outline: red solid 1px;

  /* 500 px if the width of the parent element is ≥ 999 px,
   * 300 px if the width of the parent element is ≤ 600 px,
   * 50% of the width of the parent element otherwise. */
  max-width: 500px; min-width: 300px; width: 50%;
}

p#outputBodyWidth { color: blue; }
p#outputDivWidth { color: red; }
<div>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
  eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  <p id="outputDivWidth"></p>
</div>
<p id="outputBodyWidth"></p>

Here is the part that I don't like:

reportWidths();
window.addEventListener('resize', () => {
  reportWidths();
});

It looks silly and unprofessional to me (note, I'm not really a web developer) to use function call right before using event listener that uses the same function, and so I would prefer to change it to a one-step solution. But how?



from To merge window resizing and loading the page events into one function

No comments:

Post a Comment