Search code examples
javascriptnext.jsresize-observer

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*/}

Solution

  • 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);