Reputation: 784
This is not a duplicate of the question above
I use material-icons
on my website. In order to add an icon, you'd have to make something like this:
<p class="material-icons">info_outline</p>
If I now copy that icon, it would copy the text "info_outline". I know you can make an element unselectable using user-select: none;
inside you css
, but there is a problem with that.
Take my snippet for example. If I create an p
element, with a span
inside which has user-select: none;
you won't be able to select (and therefor copy) the span. However, if you copy the whole p
element, you will still get the contents of the span
. How can I prevent this from happening?
span {
user-select: none;
}
input {
width: 100%;
}
<p>Copy this text with a <span>unselectable</span> piece of text... Or is it?</p>
<input type="text" placeholder="Past text here">
Edit:
Since a lot of people say it's a duplicate question to the questions where the answer is user-select: none;
, just take another look at my question.
I know how user-select works. I know you can make an element unelectable. However, if you select the element around it and copy it's contents, it will copy all it's content, even the element with the user-select: none;
Upvotes: 15
Views: 23618
Reputation: 1836
First of all make the element unselectable:
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
This already works in Firefox. To get it work in other browsers, you have to work with pseudo-elements
and data-attribute
.
Use a data-attribute
like this:
<span data-unselectable="unselectable content"></span>
Now we can add this text in the content of our pseudo-element ::before
or ::after
:
span::before {
content: attr(data-unselectable);
}
This works because the dom
will not be updated by the content attribute.
Upvotes: 22
Reputation: 181
Add css style
.youClass {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
Or if you want make it better use script some thing like this.
<script>
window.onload = function() {
var labels = document.getElementsByTagName('label');
for (var i = 0; i < labels.length; i++) {
disableSelection(labels[i]);
}
};
function disableSelection(element) {
if (typeof element.onselectstart != 'undefined') {
element.onselectstart = function() { return false; };
} else if (typeof element.style.MozUserSelect != 'undefined') {
element.style.MozUserSelect = 'none';
} else {
element.onmousedown = function() { return false; };
}
}
</script>
Upvotes: 2