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 :
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>