0

I'm storing window width into a variable using const deviceWidth = window.innerWidth;. This is great however, I would like the variable to update anytime the user resizes the window. How is this achieved?

Eric Nguyen
  • 612
  • 1
  • 7
  • 20
  • Since it varies, don't save it as a constant. Use `var` or `let` instead. – Ibu May 31 '19 at 22:37
  • 3
    Possible duplicate of [JavaScript window resize event](https://stackoverflow.com/questions/641857/javascript-window-resize-event) – Ibu May 31 '19 at 22:39
  • Unfortunately, that is very little context. Why copy the value of `innerWidth` to a const variable? Why not just read it from `window` directly when you want to observe any changes done somwhere else? Or is it an `Observable` what you really want? Something with an `eventListener` that triggers? – Marvin H. May 31 '19 at 22:41

2 Answers2

0

I would leverage the window resize event to keep your variable updated:

https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event

Essentially, you can create a function that is ran on any window resize and then set your variable.

const heightOutput = document.querySelector('#height');
const widthOutput = document.querySelector('#width');

function reportWindowSize() {
  heightOutput.textContent = window.innerHeight;
  widthOutput.textContent = window.innerWidth;
}

window.onresize = reportWindowSize;
<p>Resize the browser window to fire the <code>resize</code> event.</p>
<p>Window height: <span id="height"></span></p>
<p>Window width: <span id="width"></span></p>
mwilson
  • 10,186
  • 5
  • 41
  • 72
-1

When the window changes size it triggers a 'resize' event. Details here

You need to listen out for this event and update your variable accordingly. Details here

kevmc
  • 1,159
  • 6
  • 8