Explain Codes LogoExplain Codes Logo

Is there a way to make text unselectable on an HTML page?

html
unselectable-text
css-tricks
javascript-workaround
Alex KataevbyAlex Kataev·Aug 21, 2024
TLDR

Stop text selection in its tracks by applying CSS user-select: none:

.unselectable { user-select: none; } /* No touchy touchy! */

In your HTML, tag it like so:

<p class="unselectable">Try me, I dare you!</p>

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:

<p unselectable="on">Good old IE can't touch this.</p>

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:

function makeUnselectable(element) { if (element.nodeType == 1) { element.setAttribute("unselectable", "on"); // "Hands off!", declares the element } var child = element.firstChild; while (child) { makeUnselectable(child); child = child.nextSibling; // On to the next one! } } makeUnselectable(document.getElementById('myElement')); // Do your magic!

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:

.no-select { -webkit-user-select: none; /* Nope for Safari */ -moz-user-select: none; /* Negative for Firefox */ user-select: none; /* Null for everybody else */ }

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.