Can you tell me why scrolling page with the scrollbar causes text selection?

A nice solution found by chatGPT

Giugno 7, 2023

Scrolling the page with the scrollbar can sometimes cause text selection because the mouse pointer may inadvertently move over text while scrolling. When the mouse pointer is over text and you click and drag the scrollbar to scroll the page, the browser interprets this action as a text selection rather than a scroll action.

To prevent text selection when scrolling with the scrollbar, you can add the CSS user-select property to the affected elements and set it to none. Here’s an example:

body {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

This CSS will prevent text selection on the entire body of the page. If you only want to prevent text selection on specific elements, you can apply this CSS to those elements instead.

Alternatively, you can also prevent text selection by adding an event listener for the selectstart event and calling preventDefault() on the event. Here’s an example:

$(document).on('selectstart', function(event) {
  event.preventDefault();
});

This code will prevent text selection on the entire document by calling preventDefault() on the selectstart event.

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.