Is there a way to make text unselectable on an HTML page?
Stop text selection in its tracks by applying CSS user-select: none
:
In your HTML, tag it like so:
This universally accepted method blocks text selection across most modern browsers.
Compatibility considerations and the 'unselectable' attribute
Although the CSS method works wonders, older browsers, like some versions of Internet Explorer, can be a bit disobedient. In such cases, the unselectable
attribute set to "on" keeps the text unselectable:
This attribute, while non-standard, still works in conjunction with the CSS rule to ensure backward compatibility.
Using JavaScript for the stubborn ones
For dynamic or hard-to-reach elements, or when CSS just won't do the trick, we turn to the reliable workhorse: JavaScript:
This script travels through every child of an element, imprinting them with the unselectable attribute.
Practical applications and potential pitfalls
Sometimes interactivity demands unselectable text, like in buttons or features that might get messed up with text selection. However, moderation is key! Overuse can turn this useful trick into a navigational nightmare.
Account for all browsers
Cover all bases by adding -moz-user-select
and -webkit-user-select
together with the user-select
rule for compatibility across all browsers:
Be wary of double-clicks
In some UIs, double-clicks accelerate user interactions. Adding user-select: none
to these elements ensures a cleaner visual experience.
Crediting external scripts
Using an external JavaScript? Give credit where it's due! This practise prevents potential conflicts, not just with copyright, but also with fellow coders.
Was this article helpful?