Responsive Variable for Browser Window Width [JavaScript]

1.4k Views Asked by At

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

}
2

There are 2 best solutions below

1
John Doe On

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);
}

5
uingtea On

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)
}