'Is there any DOM event listeners to detect change in height of window?

I tried window.resize event listener, but it does not fulfil my needs. It detects change in width of window. I need to detect the change of browser window's height only.

I need something like

window.addEventListener("onHeightResizeOnly", 
() => {
  console.log(window.innerHeight);
});


Solution 1:[1]

You can use the resize event and compare window.innerHeight to a previous value stored.

let previousHeight = window.innerHeight
window.addEventListener("heightChange", (event) => {
  console.log(event.type, event.detail);
});
window.addEventListener("resize", (event) => {
  if (window.innerHeight > previousHeight) {
    // bigger
    window.dispatchEvent(new CustomEvent("heightChange", {
      detail: { type: "larger", previousHeight, newHeight: window.innerHeight }
    }));
  } else if (window.innerHeight < previousHeight) {
    // smaller
    window.dispatchEvent(new CustomEvent("heightChange", {
      detail: { type: "smaller", previousHeight, newHeight: window.innerHeight }
    }));
  } else {
    // height not changed
  }
  previousHeight = window.innerHeight;
}, { capture: true, passive: false });

(try the snippet in full page-style)

Solution 2:[2]

If it doesn't need to be an event listener you can try a Resize Observer as explained here:

const resize_ob = new ResizeObserver(function(entries) {
    // since we are observing only a single element, so we access the first element in entries array
    let rect = entries[0].contentRect;

    // current height
    let height = rect.height;
    console.log('Current Height : ' + height);
});

// start observing for resize
resize_ob.observe(document.querySelector("body"));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Zach Jensz