How do I disable text selection with CSS or JavaScript?
CSS comes to the rescue for disabling text selection. Apply user-select: none
rule, and voila, text highlighting is no more across all major browsers.
Snippet:
Incorporate class="no-select"
in your HTML element:
To bolster the extent of prevention, consider supplementing the CSS approach with JavaScript, providing an extra wall against highlighting during user interactions.
Deep Dive: Methods and Considerations
Go beyond CSS: HTML attributes and JavaScript events
Boost your selection prevention power using HTML attributes and JavaScript events. Use the unselectable
attribute set to "on"
for vintage browser love, while taking advantage of onselectstart
and onmousedown
attributes to thwart selection on mouse interactions.
Be kind to users: UX and Accessibility
Disabling text selection may come with UX and accessibility consequences. Users might wish to copy text for noble purposes - like quoting your wisdom or sharing your knowledge. Therefore, disable text selection only where essential to maintain a user-friendly interface.
Cross-Browser compatibility
Ensure to test your implementation across a variety of browsers for compatibility. The user-select
property may have its fans, but it's certainly not a superstar with flawless support. So, verifying browser compatibility is crucial.
Pseudo-elements to the rescue
Where visual selection is not a crime but copying is, the ::selection
pseudo-element will come in handy. This lets you style highlighted text without breaking the "read-but-don’t-steal" rule.
Get scripty with it: JavaScript
For a more meticulous control, tap into the power of JavaScript event listeners. This will let you outsmart any cunning browser-specific selection tactics.
Snippet:
Making your interactions shine
Style your selections
Unlock the power of the ::selection
pseudo-element to customize your text selection appearance, user-select: none
for the copy protection, and you create a visually appealing experience while preserving your content.
Fine-tune your interface: Usability
When disabling text selection, always consider how it affects your users journey* and your interface's usability. Aim to make their journey as effortless as a downhill slide.
Cater for the browser bunch
Each browser is a special snowflake with its unique behaviours, keep this in mind while implementing text-selection prevention. So, tailor your solutions with JavaScript like a custom suit.
Standardization of CSS properties: A myth?
Be aware, CSS properties like user-select
might not be footprints on stone. They may change as the tide of specifications turns. So, keep your skills and your brew, strong.
Was this article helpful?