detecting pointermove event outside div while pointer is down



I was testing my skills the other day. The ultimate goal is to replace all html tags with div

Goal: create a color picker like the one in photoshop

Requirements: use H5, JS, and CSS only (I also use ReactJS for building the structure)

Already achieved:

  • use onPointerMove and onPointerDown to detect the pointer position in the viewport
  • calculate the pointer position (left / top) and position the indicator on where my pointer is
  • get the color selected in RGB

HTML structure:

let padding = props.size * 0.1;
<div className="color-picker">
    <div className='color-picker-container' style={ { width: `${props.size + 2 * padding}px` } } onPointerMove={ onMove } onPointerDown={ onMove }>
        <div className="color-picker-panel" style={ { width: `${props.size}px` } }/>
        <div className="color-picker-indicator" style={ { left: pickerPos.left, top: pickerPos.top, borderColor: `rgb(${getInvertedColorChannel(ColorChannel.R, currentMaxColor)}, ${getInvertedColorChannel(ColorChannel.G, currentMaxColor)}, ${getInvertedColorChannel(ColorChannel.B, currentMaxColor)}` } }/>
    </div>
</div>

Result:

enter image description here

Explanation:

  • background color change according to selected color
  • white part is the padding of container
  • pointer event in container for the “add padding” workaround (stated in “Problem”)
  • indicator can only move while dragging within the white area (including the color picker panel)

Problem:

  • Pointer events only fire when directly interacting with the div, so I cannot move the indicator when the pointer is down and outside the div (white area)
  • current workaround is add a padding to the color picker, but this method still has a boundary on where the interaction can be. The goal is to be able to move the indicator after pointerdown in the div even the pointer is moved from inside div to outside div.

feel free to ask for more details, thanks!

Answer

When you get the mouse down event in the div attach a mouseMove listener to <body> and track it from there. On mouse up, remove the listener.



Source: stackoverflow