0

I'm trying to have a variable that constantly updates whenever the browser window is resized in terms of width (in pixels). I do not want the page to have to refresh for the variable to change, but rather have the variable change as the window is resized.

I do not want the variable to be written in the html document either, as I use this variable mathematically further down the script before it has any effect.

Here is the closest I think I got to the answer.

window.onload = function() {
  var windowwidth = window.innerWidth;
};

window.onresize = function() {
  var windowwidth = window.innerWidth;
};

console.log(windowwidth);

ANSWER BELOW

window.onload = function() {
  currentWidth(document.body.clientWidth);
};

window.onresize = function() {
  currentWidth(document.body.clientWidth);
};

function currentWidth(w) {

// Math using w goes here

}
Nimantha
  • 6,405
  • 6
  • 28
  • 69

2 Answers2

0

Use the following JS Code at your end and resize the window. you can see the value of variable change on resizing the window.

var a = Math.random();
console.log (a);
window.onresize = function()
{
    a = Math.random();
    console.log (a);
}
John Doe
  • 1,401
  • 1
  • 3
  • 14
  • hi, sorry if I didnt explain it right. I didnt want a random number to equal the variable. I was after the width of the browser window in pixels, and have it update as the window is resized. for instance: When the window is 1920 px wide, a === 1920. When the window is 500 px wide, a === 500. – coding_beginner_but_just_wait Feb 04 '21 at 11:14
0

call the function inside the callback

window.onload = function() {
  currentWidth(window.innerWidth);
};

window.onresize = function() {
  currentWidth(window.innerWidth);
};

function currentWidth(w) {
  console.log(w)
  console.log(w > 500)
}
uingtea
  • 6,002
  • 2
  • 26
  • 40