3

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

3
  • 1
    You can use style tags and in that, you can write all your CSS if you don't want to messy the js file it is a easy way Commented Nov 25, 2022 at 6:50
  • media queries is a css thing. if you don't have access to css file, then you have to create a style tag in js, write your css in it and put it in the head tag. Commented Nov 25, 2022 at 6:56
  • @Layhout Yeah that seems to be the best option, will try doing that. Thanks! Commented Nov 25, 2022 at 7:33

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.