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.

Recommended

The Quantcast CMP broke my sites

A javascript error in CMP blocks my site.

Maggio 19, 2023

Scroll to DIV by ID without jQuery

Use scrollIntoView instead of jQuery animate.

Dicembre 16, 2022

React links

Collection of links and notes while approaching React.js, next.js and related topics.

Dicembre 14, 2022

Add Internet Explorer class to body to detect old browser

When you have clients that still uses an old browser, you need to handle it. This javascript function detects the…

Febbraio 27, 2017

Modify list counter in :before pseudo class with jQuery using start attribute

Suppose you have two ordered list ol tags, and the second one has a start attribute. You also have in…

Aprile 20, 2016

Refresh a Google Adsense banner with Javascript

Often bloggers and site owners use galleries to have a greater number of pages, adding pages means adding clicks. Each…

Novembre 9, 2013