kduan
kduan

Reputation: 659

How to display user's monitor resolution even on resize?

I was wondering if there was a way to show a user's screen information that updates when the user resizes their screen. I've seen javascript that just shows the user's screen but doesn't update in real time. Any one know the script for this? Thanks!

Upvotes: 1

Views: 357

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074198

Two thoughts:

  1. The resize event on window, but I suspect the browser won't fire on the screen-size change (might do, though, I suppose). If it doesn't the user will probably resize the window after resizing the screen... Chrome, at least, doesn't fire resize when the screen resolution changes but the browser window size doesn't. Sometimes changing the screen resolution will have the knock-on effect of changing the browser size (e.g., if it needs to be smaller, or if it's docked in some way), but frequently not.

  2. If browsers don't reliably fire resize (and I suspect they don't), you'll have to poll and check the screen object to see if the size changed. Not ideal, but polling once a second or so won't be much overhead.

Here's an example using both methods, plus window.onfocus as GitaarLAB suggested: Live Copy

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Example</title>
</head>
<body>
<script>
  (function() {
    "use strict";
    var lastSize;

    window.onfocus = window.onresize = checkSize;

    setInterval(checkSize, 1000);

    function checkSize() {
      if (!lastSize || (lastSize.width !== screen.width || lastSize.height !== screen.height)) {
        lastSize = {
          width: screen.width,
          height: screen.height
        };
        display("Screen size is (now) " + lastSize.width + "x" + lastSize.height);
      }
    }

    function display(msg) {
      var p = document.createElement('p');
      p.innerHTML = String(msg);
      document.body.appendChild(p);
    }
  })();
</script>
</body>
</html>

Of course, you only need polling if notification on window resize and window focus isn't sufficient.

Upvotes: 3

azz
azz

Reputation: 5930

How about binding a function to window.onresize?

window.onresize = function (e) {
  console.log("Dimensions: " + e.target.outerWidth + "x" + e.target.outerHeight);
};

Upvotes: 1

Related Questions