-2

This little function gives me a headache.

document.write in combination with media queries just won't work responsive.

I'm trying to change the css stylesheet with document.write as soon as the max-width changes.

It works, but not responsive - I have to reload the page.

It works perfectly fine with document.body.style.backgroundColor as example - but not with document.write.

Does anyone know why, or is there a better way?

let Swidth = window.matchMedia("(max-width: 700px)")
  function reSize(Swidth) {
    if (Swidth.matches) {
      /* document.body.style.backgroundColor = "yellow"; // This works */
      document.write('<link href="./src/css/variant1.css" type="text/css"  rel="stylesheet">');

    } else {
      
      /* document.body.style.backgroundColor = "blue"; // This works */
      document.write('<link href="./src/css/variant2.css" type="text/css"  rel="stylesheet">')

    }
  }
reSize(Swidth);
Swidth.addEventListener("change", reSize);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Blup
  • 1
  • 1
  • 2
    It's not the media queries, it's [`document.write`](https://developer.mozilla.org/en-US/docs/Web/API/Document/write), which clears the page when called after the page has been parsed. See [how to modify an existing document](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents). – Teemu Apr 29 '22 at 12:25
  • 1
    Does this answer your question? [Document.write clears page](https://stackoverflow.com/questions/10873942/document-write-clears-page) – Lee Taylor Apr 29 '22 at 12:45

2 Answers2

0

You can use the media attribute of the <link> element.

<link href="./src/css/variant1.css" type="text/css" 
      rel="stylesheet" media="screen and (max-width: 700px)">
<link href="./src/css/variant2.css" type="text/css"
      rel="stylesheet" media="not screen and (max-width: 700px)">
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
-2

This solution works for me.

function addStylesheet(theHref) {
    if (document.createStyleSheet) {
        document.createStyleSheet(theHref);
    } else {
        var newSheet = document.createElement('link');
        newSheet.setAttribute('rel', 'stylesheet');
        newSheet.setAttribute('type', 'text/css');
        newSheet.setAttribute('href', theHref);
        document.getElementsByTagName('head')[0].appendChild(newSheet);
    }
}

let Swidth = window.matchMedia("(max-width: 700px)")

function reSize(Swidth) {
    if (Swidth.matches) {
        document.body.style.backgroundColor = "yellow";
        addStylesheet("./src/css/variant1.css")
    } else {
        document.body.style.backgroundColor = "blue";
        addStylesheet("./src/css/variant2.css")
    }
}
reSize(Swidth);
Swidth.addEventListener("change", reSize);
HerrAlvé
  • 587
  • 3
  • 17
Blup
  • 1
  • 1