Make text not copied HTML
This is not a duplicate of the question above.
I am using material-icons
on my website. To add an icon, you need to do something like this:
<p class="material-icons">info_outline</p>
If I now copy this icon, it copies the text "info_outline". I know that you can make an item unselectable using user-select: none;
inside you css
, but there is a problem with that.
Take my snippet for example. If I create an element p
that has span
inside it user-select: none;
, you won't be able to select (and copy over) the range. However, if you copy the entire element p
, you still get the content span
. How can I prevent this?
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 this is a duplicate question to the questions answered user-select: none;
, just take a look at my question.
I know how custom selection works! I know you can make an item unselectable. However, if you select an element around it and copy its content, it will copy all content, even the element withuser-select: none;
source to share
First of all, make the item 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 make it work in other browsers you need to work with pseudo-elements
and data-attribute
.
Use data-attribute
like this:
<span data-unselectable="unselectable content"></span>
Now we can add this text to the content of our pseudo-element, ::before
or ::after
:
span::before {
content: attr(data-unselectable);
}
This works because it dom
won't update with the content attribute.
source to share
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 prefer, it is better to use a script something 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>
source to share