Home > Net >  How to change CSS media query styles dynamically using JavaScript?
How to change CSS media query styles dynamically using JavaScript?

Time:02-17

I am trying to implement a dark mode for only screens that are less than 700px. I have body background set globally for all screens, then there is JS set interval function that will change the body background color to white after sometime. @media only screen and (max-width: 700px) has its own background black set. But because of the set interval function, it will change back to white after sometime. So please help me how can I access the body background property under CSS @media only screen and (max-width: 700px) to change the background color after sometime inside the set interval function. I am looking for a JavaScript solution as already using JS. Is there any way to do it inside the JS function using CSS variable

CSS

body {       
    background: rgba(225,119,119,0.4);  
}

@media only screen and (max-width: 700px) and (orientation: portrait) {
    body {
        background: rgba(0,0,0,1); 
    }
}

JS

setInterval(function() {       
    document.body.style.background = "rgba(255,255,255,1)";
}, 292);

   /* 
   There inside the JS function I want to change body background for the css media query 
      ... 
      do I need if else conditions for this here
      like 
      if(max-width: 700px) 
      {
          document.body.style.background = "rgba(0,0,0,1)";
      } 
   */

CodePudding user response:

You can make use of the matchMedia API:

if (window.matchMedia("(max-width: 700px)").matches && window.matchMedia("(orientation: portrait)").matches) {
   // your code
}

You just have to enter the same arguments as in the CSS

  • Related