Alyona
Alyona

Reputation: 1792

Can ResizeObserver listen just to width change?

I want to trigger ResizeObserver only on width change and not use it if height was changed. Is it possible?

Example:

const resizeObserver = new ResizeObserver(setLayout);
resizeObserver.observe(layout.current);

const setLayout = () => {/*do something*/}

Upvotes: 1

Views: 2181

Answers (1)

code
code

Reputation: 6319

There isn't a built-in function, but you can make a wrapper that checks if (only) the width has changed:

const ro = function($el, cb) {
  let last = $el.getBoundingClientRect();
  const observer = new ResizeObserver(function() {
    const data = $el.getBoundingClientRect();
    if(data.width !== last.width && data.height === last.height)
      cb();
    last = data;
  });
  observer.observe($el);
}

Then use it like:

ro(layout.current, setLayout);

Upvotes: 0

Related Questions