Lily Mara
Lily Mara

Reputation: 4128

addEventListener('resize' not working for div with relative size

I'm trying to set up a resize listener for a div with a relative size. The div has a height: 100% style on it, and I would like the event to fire when the pixel height of the div changes with its parent container. Here is my basic code:

index.html

<html>
  <body>
<div class="foo"></foo>
  </body>
</html>

main.css

.foo {
  background-color: blue;
  height: 100%;
    width: 100%;
}

html, body {
  height: 100%;
  width: 100%;
}

main.js

document.querySelector(".foo").addEventListener("resize", () => {
  console.log("foo resize");
});

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

When I resize the window, I get the expected "window resize" text in the console, but "foo resize" is never printed. Is there something else that I need to do to get the foo resize handler to fire?

Upvotes: 0

Views: 974

Answers (1)

Sarah Gro&#223;
Sarah Gro&#223;

Reputation: 10879

The resize event is only fired on the window object. There's ResizeObserver in the making, allowing to observe the resizing of arbitrary elements, but browser support for it is still very scarce. There are however polyfills to mimic its behaviour, like resize-observer-polyfill on NPM.

Upvotes: 1

Related Questions