Home > Software engineering >  Using setTimeout continuously vs media query for handling different screen resolutions
Using setTimeout continuously vs media query for handling different screen resolutions

Time:12-05

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();

CodePudding user response:

Using setTimeout to check for screen width every 100ms is not a good approach for making any website responsive. Instead, you should use media queries in your CSS to specify how your website should look at different screen sizes. This will allow the browser to automatically adjust the layout of your website when the screen size changes, without needing to constantly poll the screen width using JavaScript. Using media queries is a better approach for making a website responsive because it is more efficient, maintainable, and user-friendly than constantly polling the screen width using JavaScript.

Here are a few sources that you can use to learn more about using media queries to make your website responsive:

CodePudding user response:

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>

  • Related