Search code examples
javascriptcssmedia-queries

Using CSS media queries inside a JavaScript file


I am working on an already existing webpage and want to resize some elements using CSS media queries like width but i only have access to the script file, is there a way to do this without injecting CSS in my js file?

As of now i've tried injecting my css file line by line in my js file


Solution

  • Although less than ideal, it seems that this is possible by creating a MediaQueryList object from window.matchMedia(), and set inline styles by listening to events for changes on it.

    Detailed guide on: MDN

    Here is a quick example targeting @media (max-width: 640px):

    (Open full page and try change window size to see effects)

    const body = document.querySelector("body");
    const title = document.querySelector("h1");
    
    const media = window.matchMedia("(max-width: 640px)");
    
    body.style.background = media.matches ? "pink" : "lightgreen";
    title.innerText = "Open full page and try change window size";
    
    media.addEventListener("change", (event) => {
      if (event.matches) {
        body.style.background = "pink";
        title.innerText = `Matching: ${media.media}`;
      }
      if (!event.matches) {
        body.style.background = "lightgreen";
        title.innerText = `Not matching: ${media.media}`;
      }
    });
    <h1></h1>