0

I'm trying to display the window size, whenever I resize my window. but I'm not able to until I refresh the window, I want to see the window size on the fly while I'm resizing the window.

window.onload = init();
window.onresize = init();

function init() {
  var status = document.querySelector("#pagesize");
  status.innerHTML = "" + window.innerHeight + " " + window.innerWidth;
}
#pagesize {
  border: 1px solid red;
  padding: 2px;
  color: red;
}
html code:-
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <link rel="stylesheet" href="style.css">
  <title>window resize</title>
</head>

<body>
  <p>PAGE WINDOW SIZE <span id="pagesize">NOT LOADED YET</span></p>
  <script src="script.js"></script>
</body>

</html>
Mark Baijens
  • 13,028
  • 11
  • 47
  • 73
pal
  • 25
  • 4
  • op has window.innerHeight and window.innerWidth at the bottom of the code... – Omi in a hellcat Oct 16 '19 at 15:04
  • remove the brackets here: `window.onload=init(); window.onresize=init();` should be `window.onload=init; window.onresize=init;` or else you attribute the result of the function execution (eg. `false` returned by default) to the events handlers, not the function itself (too lazy today to find the dupe) – Kaddath Oct 16 '19 at 15:12
  • Possible duplicate of [jQuery on window resize](https://stackoverflow.com/questions/9828831/jquery-on-window-resize) – Cory Danielson Oct 16 '19 at 15:19
  • This answer has a JS solution that you're looking for https://stackoverflow.com/a/9828919/749622 – Cory Danielson Oct 16 '19 at 15:19

1 Answers1

0

You need to add a reference to the function to the event handler. Or even better use addEventListener() so you don't overwrite existing handlers. You stored the result of the init() function in the event handler.

window.onload = init;
window.onresize = init;

/* or better use this */
//window.addEventListener('load', init);
//window.addEventListener('resize', init);

function init() {
  var status = document.querySelector("#pagesize");
  status.innerHTML = "" + window.innerHeight + " " + window.innerWidth;
}
#pagesize {
  border: 1px solid red;
  padding: 2px;
  color: red;
}
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <link rel="stylesheet" href="style.css">
  <title>window resize</title>
</head>

<body>
  <p>PAGE WINDOW SIZE <span id="pagesize">NOT LOADED YET</span></p>
  <script src="script.js"></script>
</body>
Mark Baijens
  • 13,028
  • 11
  • 47
  • 73