I
I
IIIu6ko2020-09-29 12:46:57
JavaScript
IIIu6ko, 2020-09-29 12:46:57

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


Give me options / ideas on how to assemble a function from this so that I can import it and use it in different files.
The array of media queries, I think, can be left inside the function, if I correct something, but it can vary from 2 to infinity.
The most important thing is that you can pass code inside the function that will fall into the desired if.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MagnusDidNotBetray, 2020-09-29
@IIIu6ko

As an example , but it looks somehow not very good, maybe someone will offer something better.

S
Steppp, 2020-09-29
@Steppp

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 question

Ask a Question

731 491 924 answers to any question