skip to Main Content

So this is my code

 const mediaQ = window.matchMedia("(max-width:500px)")

        mediaQ.addEventListener("change", function(){
            if(mediaQ.matches){
                document.getElementById("box").style.backgroundColor = "blue"
            }
            else{
                document.getElementById("box").style.backgroundColor = "red"
            }
        })
#box{
            height: 20rem;
            width: 20rem;
            background-color: red;
        }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="box"></div>
    
    <a href="index.html">Its go to this page(same page)</a> 
    <!-- but in my project it go to other html-->
</body>
</html>

the problem is when you resize your width screen to below 500px and click the link (). its seem the js media query gone and i must increase my width screen up to 500px (>500px) and resize my width screen again to below 500px to get the js media query.

what i want is when i resize my width screen to below 500px and click the link () the js media query not gone.

2

Answers


  1. Your function only fires when the change event is called. You also need to check when the page is loaded.

    This can easily be achieved with a named function. See below for an example.

    const mediaQ = window.matchMedia("(max-width:500px)")
    
    function checkMediaQ() {
      if (mediaQ.matches) {
        document.getElementById("box").style.backgroundColor = "blue"
      } else {
        document.getElementById("box").style.backgroundColor = "red"
      }
    }
    
    // Check for a change.
    mediaQ.addEventListener("change", checkMediaQ);
    
    // Check on page load.
    document.addEventListener('DOMContentLoaded', checkMediaQ);
    #box {
      height: 20rem;
      width: 20rem;
      background-color: red;
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    
    <body>
      <div id="box"></div>
    
      <a href="index.html">Its go to this page(same page)</a>
      <!-- but in my project it go to other html-->
    </body>
    
    </html>
    Login or Signup to reply.
  2. Another solution is to use media querries directly in your css, which would give you easier access to your class or id.
    Here you can find how to do it.
    Media queries (w3schools)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search