Articles → JavaScript → Disable Text Selection Using Javascript
Disable Text Selection Using Javascript
- Create a div tag and add contents into it.
- Create a JavaScript function
- 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