Prevent select on input text field
It can be done by setting the element's selectionStart
to selectionEnd
on select
event:
var inp = document.getElementById('my_input');
inp.addEventListener('select', function() {
this.selectionStart = this.selectionEnd;
}, false);
<input id="my_input" type="text" value="Try to select me!" />
CSS-only solution:
This will not allow for input text to visually appear selected, while it is.
There are situations where this technique is good enough, if the developer do not care for the input's text to be able to be copy-pasted, but only the visual aspect of the selection is unwanted.
input{ color:transparent }
input::selection{ color:transparent }
<input value='invisible selection'>
It's also possible to use font-size:0
if width
& height
are defined on the input
element.
JS Solution:
When the input gets focused → unfocus it (by calling the blur
method):
<input value='unselectable selection' onfocus='this.blur()'>
You can cover over the <input>
with any layer in absolute position, for example with div.wrapper::after
or with other wrapper tag. Then use user-select: none
for the wrapper tag (<div>
, <label>
, etc) and don't use user-select: none
on the <input>
itself.
But if your wrapper tag is <label>
I recommend additionally adding the attribute readonly
for the <input>
and converting <label>
to the block (or inline-block / flex / inline-flex).
input { outline: none; margin: 10px 0; width: 200px; }
.wrapper {
position: relative;
user-select: none;
}
.wrapper::after {
content: '';
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
label.wrapper { display: block; }
<div class="wrapper">
<input type="text" value="Any text in the div wrapper"/>
</div>
<label class="wrapper">
<input type="text" value="Any text in the label wrapper" readonly />
</label>
You can prevent the mousedown
event to prevent the selection of the text inside the input
.
<input type="text" id="unselectable" value="You can not select this text!"/>
<script>
document.getElementById("unselectable").addEventListener("mousedown", function(event){
event.preventDefault();
});
</script>