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:
- The MDN Web Docs page on media queries: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
- The CSS-Tricks page on media queries: https://css-tricks.com/snippets/css/media-queries-for-standard-devices/
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>