How do I disable text selection with CSS or JavaScript?
How do I disable text selection with CSS or JavaScript?
39927-Apr-2023
Updated on 04-Dec-2023
Home / DeveloperSection / Forums / How do I disable text selection with CSS or JavaScript?
How do I disable text selection with CSS or JavaScript?
Gulshan Negi
04-Dec-2023In CSS, you can disable text selection with below code:
/* Disable text selection for the entire document */
body {
user-select: none;
}
/* Disable text selection for a specific element */
.disable-selection {
user-select: none;
}
In JS you can do same by following code:
// Using event listeners to prevent default behavior for text selection events
function disableTextSelection() {
document.addEventListener('selectstart', function (e) {
e.preventDefault();
});
document.addEventListener('contextmenu', function (e) {
e.preventDefault();
});
}
// Call the function to disable text selection
disableTextSelection();
I hope it will helps you.
Thanks