Explain Codes LogoExplain Codes Logo

Get the Highlighted/Selected text

javascript
prompt-engineering
best-practices
accessibility
Anton ShumikhinbyAnton Shumikhin·Sep 3, 2024
TLDR

Effortlessly obtain a user's selected text in JavaScript using the window.getSelection() function:

const selectedText = window.getSelection().toString(); alert(selectedText);

Execute it and voila! An alert presenting your highlighted text on the page.

Compatibility and exceptional handling

When dealing with selected text from <textarea> or <input> elements, we use a different ballgame. The selectionStart and selectionEnd properties wind up to our rescue:

function getSelectedTextFromInput(element) { return element.value.substring(element.selectionStart, element.selectionEnd); }

Safeguard cross-browser compatibility. Old versions of Internet Explorer (IE) don't play well with window.getSelection(). We use document.selection.createRange().text for these legacy bad boys:

function getSelectedText() { if (window.getSelection) { return window.getSelection().toString(); } else if (document.selection) { // Dinosaur Browser Support (IE <= 8) return document.selection.createRange().text; } return ''; }

To give your code that adrenaline shot, exclude the IE <= 8 support when it's not in your user demographic.

Real-time selection detection

Add document.onmouseup, document.onkeyup, and document.onselectionchange listeners for instant text selection updates. These gates of code allow the magic to happen whenever the user selects text:

document.addEventListener('mouseup', () => { const selectedText = getSelectedText(); if(selectedText) { console.log('Mouse whispered: ', selectedText); } }); document.addEventListener('keyup', () => { const activeElement = document.activeElement; const tagName = activeElement.tagName.toLowerCase(); if(tagName === 'textarea' || (tagName === 'input' && activeElement.type === 'text')) { const selectedText = getSelectedTextFromInput(activeElement); if(selectedText) { console.log('Key sneezed: ', selectedText); } } }); document.addEventListener('selectionchange', () => { console.log('Selection did its thing: ', getSelectedText()); });

Leverage on user selection

Enhance user interaction by incorporating custom copy or share features. Use the retrieved selected text to either copy to the clipboard or unleash it to the social media wilderness:

function copySelectedText() { const text = getSelectedText(); if (navigator.clipboard && text) { navigator.clipboard.writeText(text).then(() => { console.log('Text enjoyed its ride to the clipboard 🎢'); }); } }

Also, consider tracking what content the users frequently choose for insightful analytics. Be tactful while handling their navigational patterns.

Analyzing Mission: User Selection

You can put your Sherlock Holmes hat on and analyze the selected text for later use. Map user preferences or deliver personalized content based on their apparent interests:

let userSelections = []; document.addEventListener('mouseup', () => { const text = getSelectedText(); if(text) { userSelections.push(text); analyzeSelections(userSelections); } }); function analyzeSelections(selections) { // Sherlock mode on 👀 // Find out what text is getting user love. This would guide content refinement. }

Best Practices: Accessibility & UX

When fiddling with selections, don't forget about accessibility. Make sure your flashy features don't turn out to be hurdles for keyboard navigation or screen reader usage:

  • Introduce keyboard shortcuts for custom selection actions.
  • Voice out selection changes with ARIA live regions for screen reader users.
  • Maintain a visual focus ring for selected text, for users who need it.

Saving the day: Cross-Device Consistency

Who said this fun is meant for desktops only? Make the experience ubiquitous across devices for a flawless user environment. Whether it's swipes on a tablet or a tap on a phone, all users deserve these features!