20

I'd like to detect widnow resize event using ResizeObserver

currenlty I use

window.addEventListener('resize',() => console.log('resize'));

I want to refactor it and use ResizeObserver. Is it possible?

1 Answer 1

23

You can observe document.body.

new ResizeObserver(() => {
  console.log('resized')
}).observe(document.body)

Sign up to request clarification or add additional context in comments.

9 Comments

My opinion is that this method does not have better performance.
This only gets triggered if you resize the window's width. Resizing the window's height doesn't change the size of the body hence this event never gets triggered.
@neojp does window.addEventListener('resize') get triggered when height changes?
It's not a bug, because your code is observing the body. The body won't change its height based on the window's height.
So I'm guessing you could set the height style to 100% for <body> and it will observe
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.