Responsive layout handle with Javascript use Media Queries

Normally, we handle responsive for the UI with CSS Media Queries, but we have another way to approach this. That is Javascript, in this snippet, we will known how to it work.

We use the window.matchMedia() method, it will returns a MediaQueryList object representing the results of the specified CSS media query string. See the example codes below:

function UIHandle(matchMediaValue) {
 const elem = document.getElementById("app");
 if (matchMediaValue.matches) {
  elem.style.width = "100%";
  elem.style.margin = 0;
  elem.style.backgroundColor = "rgb(47, 83, 202)";
 } else {
  elem.style.width = "400px";
  elem.style.margin = "20px";
  elem.style.backgroundColor = "red";
 }
}

// change style of the element when the window width is less then or equal to 800px wide
const matchMediaValue = window.matchMedia("(max-width: 800px)");
UIHandle(matchMediaValue);
matchMediaValue.addListener(UIHandle);
Copy this code


In the Javascript codes above, we use the addListener method for listen and run the UIHandle function every time when the UI layout changes. You also can use the removeListener for remove the listener you added.

See demo below, resize the window to see the result: