Javascript: disable text selection
I use JavaScript to disable text selection on my website.
The code:
<script type="text/JavaScript"> function disableselect(e) { return false } function reEnable() { return true } document.onselectstart = new Function ("return false") if (window.sidebar) { document.onmousedown = disableselect document.onclick = reEnable } </script> A similar script can be found here.
On my localhost: all browsers (Firefox, Chrome, IE and Safari) work fine.
On my Live site: everything is fine except Firefox.
My questions:
Does anyone have any suggestions as to why Firefox behaves differently for a live site and localhost. Note: Javascript is included.
Maybe my script is too simplistic, so I tried the following with EXACTLY SAME Results
Just use this css method:
body{ -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } Here you can find the same answer: How do I turn off text selection highlighting using CSS?
I am writing a slider ui control to provide a drag and drop function, this is my way to prevent the content from being selected when dragging the user:
function disableSelect(event) { event.preventDefault(); } function startDrag(event) { window.addEventListener('mouseup', onDragEnd); window.addEventListener('selectstart', disableSelect); // ... my other code } function onDragEnd() { window.removeEventListener('mouseup', onDragEnd); window.removeEventListener('selectstart', disableSelect); // ... my other code } bind startDrag to your dom:
<button onmousedown="startDrag">...</button> If you want to statically disable text selection in the entire element, execute the code when loading the elements:
window.addEventListener('selectstart', function(e){ e.preventDefault(); }); For JavaScript, use this function:
function disableselect(e) {return false} document.onselectstart = new Function (return false) document.onmousedown = disableselect To enable selection:
function reEnable() {return true} and use this function anywhere:
document.onclick = reEnable If you got an HTML page like this:
<body
onbeforecopy = "return false"
ondragstart = "return false"
onselectstart = "return false"
oncontextmenu = "return false"
onselect = "document.selection.empty ()"
oncopy = "document.selection.empty ()">
There is an easy way to disable all events:
document.write(document.body.innerHTML)
You got HTML content and lost other things.
Just copy this text and put it before </body>
function disableselect(e) { return false } function reEnable() { return true } document.onselectstart = new Function ("return false") if (window.sidebar) { document.onmousedown = disableselect document.onclick = reEnable } You can also use:
onselectstart = (e) => {e.preventDefault()} Example:
Another alternative, by testing CSS support and disabling user selection: