Answer the question
In order to leave comments, you need to log in
How to make a function for media queries in js?
There is such a code with media queries for js.
const mqList = [
window.matchMedia('(min-width: 0px) and (max-width: 768px)'),
window.matchMedia('(min-width: 768px) and (max-width: 992px)'),
window.matchMedia('(min-width: 992px)'),
];
function mqIf() {
if (mqList[0].matches) {
document.querySelector('body').style.background = 'red';
}
if (mqList[1].matches) {
document.querySelector('body').style.background = 'white';
}
if (mqList[2].matches) {
document.querySelector('body').style.background = 'green';
}
}
mqIf();
for (let i = 0; i < mqList.length; i += 1) {
mqList[i].addEventListener('change', mqIf);
}
Answer the question
In order to leave comments, you need to log in
As an example , but it looks somehow not very good, maybe someone will offer something better.
export const Media = () => {
const mqList = [
window.matchMedia('(min-width: 0px) and (max-width: 768px)'),
window.matchMedia('(min-width: 768px) and (max-width: 992px)'),
window.matchMedia('(min-width: 992px)'),
];
function mqIf() {
if (mqList[0].matches) {
document.querySelector('body').style.background = 'red';
}
if (mqList[1].matches) {
document.querySelector('body').style.background = 'white';
}
if (mqList[2].matches) {
document.querySelector('body').style.background = 'green';
}
}
mqIf();
for (let i = 0; i < mqList.length; i += 1) {
mqList[i].addEventListener('change', mqIf);
}
};
import media from './file-name.js';
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question