Selecting text in an element (akin to highlighting with your mouse)
Do a lightning-fast highlighting of text from a DOM element by harnessing the power of window.getSelection()
along with document.createRange()
:
To get this working, all you need to do is swap 'targetElement'
with the ID of the desired element. This efficient snippet creates a boundary enclosing the contents of the element, manifesting the visual effect of a mouse-generated highlight.
Putting code into context
Case of non-input elements
Our code above is a hardworker. It doesn't discriminate between input or non-input elements like divs, spans, or paragraphs.
Iframes: a unique canvas
When you're dealing with iframes, ensure you've got the right document. And also, remember, security is key! Keep your operations snug within the same domain.
jQuery version: all too familiar
If jQuery prides itself as your go-to syntax, a plugin is probably your favorite rave. Here's how our function looks in jQuery style:
This lets you enjoy jQuery's chained syntax and readability.
Enhancing for broader use cases
Mobile devices: the modern norm
Reflect upon mobile device prevalence and make sure your methods translate well on touch events. Use touchstart
and touchend
to detect gestures resulting in text highlighting.
Keyboard enthusiasts: they exist
Design for users who are keyboard-dependent. Listen for keydown
events and invoke text highlighting once detecting the preferred keyboard shortcut.
Dynamic contents & SPAs: the next-gen web
In Single Page Applications (SPAs) or sites with dynamically loaded contents, consider using a MutationObserver to keep tabs on DOM changes and highlight newly inserted elements.
Accessibility: inclusivity matters
Never forget accessibility. Selections may disrupt the flow for users who depend on screen readers. Make sure they can use your feature and that it's announced correctly by assistive technologies.
Security: always critical
Be cognizant of security implications when dealing with cross-origin iframes or user-generated content. Sanitize user inputs and strictly adhere to the Content Security Policy (CSP) best practices.
Was this article helpful?