How to make HTML Text unselectable
Need your text to become a ninja and avoid the grip of a cursor? Use the CSS user-select: none
:
Then, apply to your HTML element that you wish to be 'ninja-like':
Voila! Your text is now unselectable and stealthy enough to avoid those pesky cursors across all modern browsers.
Nitty-gritty: Cross-browser support and more
Making your text unselectable will save it from becoming an easy prey. But before we proceed, please consider the ramifications of such action. Remember, with great power comes great responsibility!
Working across browser timelines
Although user-select: none
works as a ninja in modern browsers, we need to ensure its stealthiness remains even in older browsers. Equip it with its stealth weapons – vendor prefixes:
JavaScript: Treatment for Amnesiac Browsers
For those browsers that suffer from chronic amnesia, forgetting all about CSS, we call upon JavaScript to remind them how to keep our text unselectable:
Making jQuery work for us
You can delegate the task to jQuery. It can ensure that all elements, even those who are notoriously late to the party, won't get selected:
The Over-enthusiastic Selectors
Remember, only apply the unselectable class where necessary. Save yourself from being that person, applying a property globally and then wondering why it isn't working!
Good power, Good responsibility
Before you switch to stealth mode, remember, it might confuse your users. So think twice, code once!
Tackling specific scenarios: the right tool for the right job
Did you find your elements in a mess after preventing text selection? Perhaps you need to consider two additional things.
Crafting the art of invisibility
Random selection of HTML elements for the unselectability treatment can result in unforeseen consequences! Be wise!
Keeping the Cursor Calm
Despite your text acting like ninjas, the cursor is not your enemy. Keep it normal even on hover:
Was this article helpful?