You can detect when text is selected in JavaScript by using the `selectionchange` event. Then you can use the `getSelection()` method to get the selected text and its position.
Here's an example:
```
document.addEventListener('selectionchange', () => {
const selection = window.getSelection();
if (selection.type === 'Range') {
const selectedText = selection.toString();
const startPosition = selection.anchorOffset;
const endPosition = selection.focusOffset;
console.log('Selected Text:', selectedText);
console.log('Start Position:', startPosition);
console.log('End Position:', endPosition);
}
});
```
This code adds an event listener to the `document` that listens for the `selectionchange` event. When that event is fired, it checks if a range of text is selected (`selection.type === 'Range'`). If text is selected, it gets the selected text using `selection.toString()` and the start and end position using `selection.anchorOffset` and `selection.focusOffset`, respectively. These values represent the cursor positions of the start and end of the selection within the selected text.