Articles → JavaScript → Disable Text Selection Using Javascript

Disable Text Selection Using Javascript









  1. Create a div tag and add contents into it.
  2. Create a JavaScript function
  3. Call the JavaScript function.

Create A Div Tag And Add Contents Into It


<div id="mydiv">
Welcome to Gyan Sangrah: A one stop shop for people preparing for technical interviews. 
Gyansangrah is an online resource comprising all the possible questions you may face during your technical 
interview round. Gyansangrah also provides you with live examples to make concepts easier to understand.
</div>





Create A Javascript Function




<script type="text/javascript">
  function disableSelection(target) {
  if (typeof target.onselectstart != "undefined") //IE route   
    target.onselectstart = function() {
      return false
    }
  else if (typeof target.style.MozUserSelect != "undefined") //Firefox route
  {
    if (typeof target.style.MozUserSelect != "none") {
      target.style.MozUserSelect = "none";
    }
  } else //All other route (ie: Opera)   
    target.onmousedown = function() {
      return false
    }
}
</script>










{-moz-user-select: none;}















Call The Javascript Function


<script type="text/javascript">
  disableSelection(document.getElementById("mydiv"));
</script>



Code


<!DOCTYPE html>
<html>
<head>
    <title>Disable Text using JavaScript</title>
    <script type="text/javascript">
        function disableSelection(target) {
            if (typeof target.onselectstart != "undefined") {
                // IE route
                target.onselectstart = function () { return false; };
            } else if (typeof target.style.MozUserSelect != "undefined") {
                // Firefox route
                if (typeof target.style.MozUserSelect != "none") {
                    target.style.MozUserSelect = "none";
                }
            } else {
                // All other route (e.g., Opera)
                target.onmousedown = function () { return false; };
            }
        }
    </script>
    <style type="text/css">
        #mydiv {
            -moz-user-select: none;
        }
    </style>
</head>
<body>
    <form id="form1">
        <div id="mydiv">
            Welcome to Gyan Sangrah: A one stop shop for people preparing for technical interviews.
            Gyansangrah is an online resource comprising all the possible questions you may
            face during your technical interview round. Gyansangrah also provides you with live
            examples to make concepts easier to understand.
        </div>
    </form>
    <script type="text/javascript">
        disableSelection(document.getElementById("mydiv"));
    </script>
</body>
</html>

Try It


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, August 18, 2011

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250