0

Using VanillaJS, how do I update the value of a variable when the browser window is resized? The main goal for my project is to track how far down the user is on a page given the page's height.

var clientHeight = document.body.clientHeight;
var clientHeight25 = clientHeight * .25;
var clientHeight50 = clientHeight * .50;
var clientHeight75 = clientHeight * .75;

Let's say for this example clientHeight equals 1000. When I resize the browser window, its value increases to 1500. When I check the value of clientHeight50 in the console after the browser has resized, its value is the same as before (500). What is the best way to update this without creating pollution in the console?

subwaymaps
  • 15
  • 3

1 Answers1

2

You could listen for the window resize event and update your variables when it occurs:

window.addEventListener("resize", function(event) {
  // update your variables
});

You might additionally want to listen for orientation changes.

Also have a look at the scroll event as pointed out by @PHPglue in the comments.

Community
  • 1
  • 1
le_m
  • 15,910
  • 7
  • 55
  • 65