HTML Change Class Name Based on Screen Size

I am trying to change the name of a class tag dynamically when a user loads the page based off of the screen size. Here is the code:

<!DOCTYPE html>
<html>
<body onload="changeClass()">

<section class="example">
    <p>Hello</p>
</section>

<section class="example">
    <p>New section</p>
</section>

<script>
function changeClass() {
    var x = document.getElementsByClassName('example');
    var width = (window.innerHeight > 0) ? window.innerHeight : screen.Height;
    console.log(width);
    if(width <= 640) {
        while(x.length > 0) {
            x[1].className ='newClass'; 
        }
    } else {
        while(x.length > 0) {
            x[0].className = "example";
        }
    }
}
</script>
</body>
</html>

However, the page is thrown into an infinite loop and cannot load the data. Is there an easy way to set the class named based on the size of the screen? Can I use an "if conditional" check when the page loads? I have also included a JSFiddle. I don't know how much that will help however.

Answers 1

  • There are couple of problems that I can see in your code. The first thing is the way you are getting the screen width is incorrect.

    it should be corrected as below.

    var width = (window.innerWidth > 0) ? window.innerWidth : screen.Width;
    

    And the second thing is you don't need any loop at all. Just following code will be more than enough to achieve what you are looking for.

    function changeClass() {
        var x = document.getElementsByClassName('example');
        var width = (window.innerWidth > 0) ? window.innerWidth : screen.Width;
        console.log(width);
        if(x.length > 0) {
            if(width <= 640) {
                x[1].className ='newClass'; 
            } else {
                x[0].className = "example";
            }
        }
    }
    

Related Articles