Search code examples
javascripthtmlcsstouchtouch-event

Preventing tap-and-hold from selecting nearby text


If a user taps and holds their finger on both iOS and Android, the native browser behavior is to highlight the nearest selectable text.

I'm building a webapp where there is a chart similar to the chart in the iOS Stocks app, where you can tap the chart for details about a specific point, and slide your finger along the chart for details about different points.

The interaction is working fine, but both platforms are still selecting the text beneath the chart when the user taps and holds.

I am starting the interaction using the touchstart event, and updating what is displayed on the chart during touchmove. Both events call stopPropagation() and preventDefault().

Is there something I can do to tell the browser to not select the text underneath the chart?

Note: I do not want to set user-select: noselect on the text beneath the chart, as I do want the text to be selectable otherwise. Also, these charts can be moved around, and I won't always know what text is beneath them.

If it helps, here's an image of the UI I'm talking about, taken on iOS. This screenshot was taken after I tapped and held the chart. As you can see, it highlighted "Withdrawals". This same behavior occurs on Android.

enter image description here


Solution

  • Working solution : Add user-select: noselect on your document when touchstart is called and remove it then

    Prefixes for compatibility with all browsers user-select compatibility for browsers