Skip to content

JavaScript detects screen size responsive | Code

Simply use the width and height property of the window.screen object to get the resolution of the screen (i.e. width and height of the screen).

screen.width
screen.height

Bonus: Firefox now has “Responsive Design Mode” Which is the best for doing responsive testing that I’ve seen on any browser.

The shortcut is Cntrl+Shift+M and you’re in a fantastic mobile view with complete control over the size of the screen whilst still being able to open the dev tools.

JavaScript detects screen size responsively

A simple example code detects Screen Resolution.

<!DOCTYPE html>
<html>
<body>
  <script>
    function getResolution() {
      Console.log("Screen resolution is: " + screen.width + "x" + screen.height);
    }
  </script>

  <button type="button" onclick="getResolution();">Get Resolution</button>
</body>
</html>

Output:

JavaScript detects screen size responsive

Detect screen size change

window.onresize = function(){
console.log("resize");
}

JavaScript easy resize for screen size

This code allows for an Obj instance to run methods on – to call code when a screen change occurs.

//https://cdnjs.cloudflare.com/ajax/libs/enquire.js/2.1.6/enquire.min.js

class ScreenSize{

    addCSS(maxOrMin, screenSize, element, style, change){
     enquire.register("screen and ("+maxOrMin+"-width: "+screenSize+")", ()=>{    
       document.querySelector(element).style[style] = change;
    });
  }
}

Do comment if you have any doubts or suggestions on this Js screen topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *