Prevent selection in HTML
To prevent text selection in your web page, the crux is applying the CSS user-select: none;
property on elements. Here's a brief one-liner to disable selection across the entire webpage:
Legacy browser support
It's not a secret that some older versions of browsers can be pretty stubborn, specifically old IE and Opera versions. For these, we use the unselectable
attribute. Let's see this antiquity at work:
Unselectability and dynamic content
Dynamic content too, like everything else on your page, has feelings and wishes to be "unselectable". Let's make that happen by utilizing recursion.
Event-level mousedown prevention
Fun fact: sometimes CSS has its limits, and interactions like dragging laugh in its face. That's when we call JavaScript to the rescue:
And jQuery can make managing this even simpler:
Vendor prefixes and pseudo-selection style
The beauty of modern browsers is their individuality - that's why vendor-specific prefixes for our CSS is an essential practice:
Don't forget to adjust highlighting styles if you've customized using ::selection
or ::-moz-selection
:
Consider UX and accessibility
From an ethical standpoint, it's important to ponder on how disabling selection may affect interaction and accessibility. Any limiting feature should be considered for its potential limitations on the user experience.
Other interaction prevention methods
You may wish to stop users from dragging images on your pages. To do this without affecting text selection, we deal with this separately:
For older browsers, here's a trick using a transparent overlay:
Precision in selection behavior
Dynamic elements and refresh standards
In dynamic web environments, refreshing the user interface during interactions helps maintain smooth user experience:
Image layering with z-index
For overlapping elements like overlays on images, manage their z-index for layering maintenance:
Event listener clean-up
Managing events efficiently necessitate removing event listeners when not in use, especially for single-page applications and dynamic content:
Was this article helpful?