JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<title>Text Selection Demo</title>
<style>
#text {
margin-top: 20px;
}
</style>
</head>
<body>
<p id="text">This is some sample text. Please select part of it and then type in the input box below.</p>
<input type="text" id="input" placeholder="Type something here...">
<button id="printButton">Print selected text</button>
<script>
const inputElement = document.getElementById('input');
const printButton = document.getElementById('printButton');
// Function to print selection range within the input field
function printInputSelection() {
const selectionStart = inputElement.selectionStart;
const selectionEnd = inputElement.selectionEnd;
console.log('Input field selection start:', selectionStart);
console.log('Input field selection end:', selectionEnd);
}
// Event listeners for input and click to capture selection range within the input field
inputElement.addEventListener('input', printInputSelection);
inputElement.addEventListener('click', printInputSelection);
// Event listener for mouseup to capture and print the range of the selection within the static text
document.addEventListener('mouseup', () => {
const selection = window.getSelection();
if (selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
/* console.log('Static text selection range:', range); */
/* console.log('Start container:', range.startContainer); */
console.log('Start offset:', range.startOffset);
/* console.log('End container:', range.endContainer); */
console.log('End offset:', range.endOffset);
console.log('Selected text:', range.toString());
}
});
// Event listener for button click to print input field value
printButton.addEventListener('click', () => {
console.log('Input field value:',...