mvasin / react-div-100vh

A workaround for the '100vh' issue in mobile browsers

Home Page:https://react-div-100vh.vercel.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[mobile]: resize event on keyboard open

nichita-pasecinic opened this issue · comments

On mobile, the resize event is triggered on input focus (keyboard open), but this should not be the case as it does not make any sense to shift the layout when keyboard is opened.

q2: Why not using orientationchange on mobile devices too ?

+++ have the same issue on mobile with opened keyboard (android). In my case opened keyboard (especially with extra height) triggers landscape layout.

@anjeypakulnevich I've found a work around, but unfortunately is not bullet proof and for me it works in most of the cases, but just does not work on Tablets landscape (idk why)

interface Props {
  maxWidth?: number;
}

export const useVH = ({ maxWidth }: Props = {}) => {
  const isTouchDevice = useIsTouchDevice();

  const setVH = () => {
    const { innerWidth, innerHeight, outerHeight } = window;

    /** On mobile, keyboard open event triggers a `resize` that we should ignore */
    const resizeTriggeredByKeyboardOpen =
      document?.activeElement?.getAttribute('type') === 'text';

    if (!resizeTriggeredByKeyboardOpen) {
      const vh = innerHeight * 0.01;
      document.documentElement.style.setProperty('--vh', `${vh}px`);
      const vhTotal = outerHeight * 0.01;
      document.documentElement.style.setProperty('--vh-total', `${vhTotal}px`);
      const width = maxWidth && innerWidth > maxWidth ? maxWidth : innerWidth;
      document.documentElement.style.setProperty('--vw', width * 0.01 + 'px');
    }
  };

  useEffect(() => {
    const dSetVH = debounce(setVH, 150);
    setVH();

    if (isTouchDevice) window.addEventListener('orientationchange', dSetVH);
    window.addEventListener('resize', dSetVH);
    return () => {
      if (isTouchDevice)
        window.removeEventListener('orientationchange', dSetVH);
      window.removeEventListener('resize', dSetVH);
    };
  }, [maxWidth, isTouchDevice]);
};

mb it can help you!