Makuhari Development Corporation
1 min read, 136 words, last updated: 2022/2/1
TwitterLinkedInFacebookEmail

How to Detect Screen Border

To detect the screen border offset -> mouseEvent.screenX

To detect if there are multiple screens -> window.screenLeft

Here is a real-world example showing how we make a collapse sidebar and let it auto-expand when user moves their mouse to the screen border.

const SIDER_TRIGGER_WIDTH = 48;
const SIDER_WIDTH = 256;
 
const handleMouseMove = (event) => {
  // mouseEvent.screenX to get the mouse position
  // window.screenLeft to get the screen offset if there are multiple screens
  const currentScreenX = event.screenX - window.screenLeft;
  if (currentScreenX <= SIDER_TRIGGER_WIDTH && isCollapsed) {
    setIsCollapsed(false);
  } else if (currentScreenX >= SIDER_WIDTH && !isCollapsed) {
    setIsCollapsed(true);
  }
};
 
<div onMouseMove={handleMouseMove}>
  ...
</div>

Notice that we always desire to define a buffer width between two change points to give a better user experience for such cases.

Makuhari Development Corporation
法人番号: 6040001134259
サイトマップ
ご利用にあたって
個人情報保護方針
個人情報取扱に関する同意事項
お問い合わせ
Copyright© Makuhari Development Corporation. All Rights Reserved.