How to set whether the text of an element can be selected or not with JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Use the userSelect property in JavaScript to enable or diable a text selection. For Firefox, use the MozUserSelect property and set it to none, to disable the selection.

You can try to run the following code to set whether the text of an element can be selected or not with JavaScript −

Example

Live Demo

<!DOCTYPE html>
<html>
   <body>
      <button onclick = "myFunction()">Click me</button>

      <div id = "box">
         Click the above button. This won't allow you to select this text. Shows ths usage of userSelect property.
      </div>

      <script>
         function myFunction() {
            var a = document.getElementById("box");
            a.style.userSelect = "none";

            // Works in Chrome and Safari
            a.style.WebkitUserSelect = "none";

            // Works in Firefox
            a.style.MozUserSelect = "none";
         }
      </script>
   </body>
   
</html>
raja
Published on 27-Feb-2018 08:21:47
Advertisements