Home >Web Front-end >JS Tutorial >How to Efficiently Detect Words Clicked on in Text with JavaScript?
Detect Words Clicked on in Text with JavaScript
When creating a JavaScript script that allows users to select words by clicking on them, the question arises: how can this be achieved efficiently and elegantly?
Verbose Method Using Class Parsing
A common but tedious approach involves parsing the entire HTML, splitting each word separated by spaces, and wrapping each word in a element. An event listener is then added to detect clicks on the word class, and the clicked word is obtained through $(this).innerHTML. While this method works, its performance and aesthetics leave much to be desired.
Optimized Solution Without Class Parsing
For a more efficient and elegant solution, consider the following:
Step 1: Capture Selection
Use window.getSelection() to capture the user's selection.
Step 2: Identify Word Boundaries
Iterate over the selection range to determine the starting and ending points of the clicked word, avoiding spaces.
Step 3: Retrieve the Clicked Word
Combine the identified characters within the selection range to form the clicked word.
Example Implementation
The following JavaScript code provides a practical implementation of this solution:
$(".clickable").click(function (e) { s = window.getSelection(); var range = s.getRangeAt(0); var node = s.anchorNode; // Find starting point while (range.toString().indexOf(' ') != 0) { range.setStart(node, (range.startOffset - 1)); } range.setStart(node, range.startOffset + 1); // Find ending point do { range.setEnd(node, range.endOffset + 1); } while ( range.toString().indexOf(' ') == -1 && range.toString().trim() != '' ); // Alert result var str = range.toString().trim(); alert(str); });
The above is the detailed content of How to Efficiently Detect Words Clicked on in Text with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!