Home >Web Front-end >JS Tutorial >How to Efficiently Detect Clicked Words in Text Without Sacrificing Performance?
Detect Clicked Words with Refinements
In the quest to enhance user interaction with text, a need arises to detect words on which users click. Addressing this, one solution involved extensive class-parsing using jQuery, creating a sluggish and visually unappealing user experience. Seeking a more elegant approach, let's delve into a refined solution.
The following JavaScript code offers a streamlined method to achieve word detection without cluttering the document with unnecessary spans:
<code class="js">$(".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); });</code>
Within the HTML document, identify the text block with the "clickable" class:
<code class="html"><p class="clickable"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris rutrum ante nunc. Proin sit amet sem purus. Aliquam malesuada egestas metus, vel ornare purus sollicitudin at. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer porta turpis ut mi pharetra rhoncus. Ut accumsan, leo quis hendrerit luctus, purus nunc suscipit libero, sit amet lacinia turpis neque gravida sapien. Nulla facilisis neque sit amet lacus ornare consectetur non ac massa. In purus quam, imperdiet eget tempor eu, consectetur eget turpis. Curabitur mauris neque, venenatis a sollicitudin consectetur, hendrerit in arcu. </p></code>
With this code, you can detect the clicked word on any part of the page, which provides a more natural user interaction without compromising performance.
The above is the detailed content of How to Efficiently Detect Clicked Words in Text Without Sacrificing Performance?. For more information, please follow other related articles on the PHP Chinese website!