Home > Back-end >  Can an element's class change depending on whether browser is widened or narrowed?
Can an element's class change depending on whether browser is widened or narrowed?

Time:11-09

I want to set a class to an element during width-change, depending on whether the browser-width is widened or narrowed. If narrowed, the element receives the first class; if widened, the second.

<--- class=“narrow”     |     ---> class=“widen”

If it can be done, my first choice is CSS, else, JavaScript (or a combo of the two). I have no idea how to approach the issue, I only know that CSS media queries is not giving me what I want.

CodePudding user response:

You can use @media. Check the size of screen, set 2 @media rules. In each rule, you can change CSS properties of the same class.

CodePudding user response:

You can use JavaScript matchMedia method as follow:

function changeClass(x) {
    if (x.matches) { // If media query matches
        document.getElementById("myDiv").classList.add("narrow");
        document.getElementById("myDiv").classList.remove("widen");
    } else {
        document.getElementById("myDiv").classList.remove("narrow");
        document.getElementById("myDiv").classList.add("widen");
    }
}

var x = window.matchMedia("(max-width: 900px) and (min-width: 400px)")
changeClass(x) // Call listener function at run time

x.addEventListener("change", () => {
    changeClass(x);
});
.narrow {
    color: red;
}

.widen {
    color: rgb(45, 230, 45);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <div id="myDiv">
        this is the div
    </div>
    
    <script src="myCode.js"></script>
</body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

If the browser width is greater than 700px it changes the class to .widen and if it is less than 700px it changes the class to .narrow.

  • Related