Home > database >  Using CSS media queries inside a JavaScript file
Using CSS media queries inside a JavaScript file

Time:11-25

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

CodePudding user response:

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>

CodePudding user response:

The best way would be to load a stylesheet that is hosted someplace you control, and then ask JavaScript to load it in the page that you want.

Code would look like:

function loadStylesheet( absPath ) {
  const linkElement = document.createElement('link');
  linkElement.rel = 'stylesheet';
  linkElement.href = absPath;
  linkElement.type = "text/css";

  const head =  document.head || document.querySelector('head');

  head.insertAdjacentElement('beforeend', linkElement);
}

Then you would call loadStylesheet() with your stylesheet's URL as the parameter.

  • Related