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

Using setTimeout continuously vs media query for handling different screen resolutions

I am trying to make my website responsive. I’m currently using setTimeout every 100ms to check for screen width and to check layouts accordingly instead of media query. Is this a bad approach or can javascript handle this since it’s a small website?

function screen() {
    var screenWidth = window.innerWidth;
    if(screenWidth < 1100) {
        if(!sidebar.classList.contains('open'))
            sidebar.style.display = 'none';
        hamburger.style.display = 'flex';
    } else {
        sidebar.style.display = 'block';
        hamburger.style.display = 'none';
    }

    setTimeout(screen, 100);
}

screen();

>Solution :

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

It’s way more readable and efficient to let css engine apply media queries for you

But if you can’t use it, it would be better if you would use matchMedia

const sidebar = document.querySelector('nav')
const hamburger = document.querySelector('button')
const mql = matchMedia('(max-width: 1100px)')
handleChange(mql)
mql.addEventListener('change', handleChange)

function handleChange(e) {
  if (e.matches) {
    if (!sidebar.classList.contains('open'))
      sidebar.style.display = 'none';
    hamburger.style.display = 'flex';
  } else {
    sidebar.style.display = 'block';
    hamburger.style.display = 'none';
  }
}
<button>-</button>
<nav>test</nav>
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