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) { = "100%"; = 0; = "rgb(47, 83, 202)";
 } else { = "400px"; = "20px"; = "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)");

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.


© 2019 4codev

Created with love by Sil.