Usama Rehan
Usama Rehan

Reputation: 175

adding media queries from js

I have a page where I open a new window like so

var myWindow = window.open("", "", "width=755.9100,height=347.7200");
myWindow.document.body.append(img);

I want to add styles some style to this new window from the previous window

@page {size: A4;margin: 0;@media print {html, body {width: 210mm;height: 297mm;}

How do I add this to head tag in html through js?

Upvotes: 4

Views: 6658

Answers (3)

Ullallulloo
Ullallulloo

Reputation: 1230

Note that checking MediaQueryList.matches does not actually add a media query to the CSS. You have to run this check every time the window changes. To do this, you should call addListener(callback) on the MediaQueryList in addition to checking the matches property directly.

For example, to apply your style to the <html> and <body> elements on printed pages:

let mediaQueryList = window.matchMedia("print");
function screenTest(e) {
    if (e.matches) {
        document.documentElement.style.width = "210mm";
        document.body.style.width = "210mm";
        document.documentElement.style.width = "297mm";
        document.body.style.width = "297mm";
    }
    else {
        document.documentElement.style.width = null;
        document.body.style.width = null;
    }
}
screenTest(mediaQueryList);
mediaQueryList.addListener(screenTest);

Upvotes: 1

kloik friend
kloik friend

Reputation: 119

style is also an HTML element, so you can append that in a similar manner as you are appending the img element

var myWindow = window.open("", "", "width=755.9100,height=347.7200");
myWindow.document.body.append(img);
var style = myWindow.document.createElement("style")
style.innerHTML = "@page {size: A4;margin: 0;@media print {html, body {width: 210mm;height: 297mm;}"
myWindow.document.head.append(style);

Upvotes: 3

Sergey
Sergey

Reputation: 5476

There is the window.matchMedia function in js:

The usage is quite simple:

if (window.matchMedia("(min-width: 400px)").matches) {
    /* the viewport is at least 400 pixels wide */
} else {
    /* the viewport is less than 400 pixels wide */
}

One more useful article is here.

Upvotes: 5

Related Questions