How to Disable Text selection on firefox in javascript - javascript

I'm using this CSS to disable text selection. It works in Chrome and Safari, but not in Firefox
*.e-pdfviewer-pageCanvas {
-moz-user-select: -moz-none !important;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
user-select: none;
}
*.e-pdfviewer-pageCanvas * {
-moz-user-select: text;
-khtml-user-select: text;
-webkit-user-select: text;
-o-user-select: text;
user-select: text;
}

With the following code you can disable text selection in the entire webpage, except inputs and textareas:
document.getElementsByTagName("BODY")[0].onselectstart = function(e) {
if (e.target.nodeName != "INPUT" && e.target.nodeName != "TEXTAREA") {
e.preventDefault();
return false;
}
return true;
};
Alternatively, if you want to disable text selection completely you can use this code:
document.getElementsByTagName("BODY")[0].onselectstart = function(e) {
e.preventDefault();
return false;
};
If you want to disable text selection only for the elements having the class .e-pdfviewer-pageCanvas you can use:
var pdfviewer = document.getElementsByClassName("e-pdfviewer-pageCanvas");
for (var i = 0; i < pdfviewer.length; i++) {
pdfviewer[i].onselectstart = function(e) {
e.preventDefault();
return false;
};
};
[EDIT]:
If none of the aforementioned solved your issue, use the following code in your HTML <body> or the element you want to disable text selection for specifically:
<body onselectstart = "return false;" style = "-moz-user-select: none;">...</body>
Or in JavaScript:
document.getElementsByTagName("BODY")[0].onselectstart = function(e) {return false};
document.getElementsByTagName("BODY")[0].style.mozUserSelect = "none";

Try this simple jQuery plugin:
jQuery.fn.extend({
disableSelection : function() {
this.each(function() {
this.onselectstart = function() { return false; };
this.unselectable = "on";
jQuery(this).css({
'-moz-user-select': 'none'
,'-o-user-select': 'none'
,'-khtml-user-select': 'none'
,'-webkit-user-select': 'none'
,'-ms-user-select': 'none'
,'user-select': 'none'
});
});
}
});
$('.e-pdfviewer-pageCanvas').disableSelection();

Related

Copy link on button click into clipboard not working

I'm currently trying to write a JS function to provide a "copy link on button click". It works fine on Android and PC but when I try it on my iPad or iPhone I'm getting an error:
TypeError: Argument 1 ('refNode') to Range.selectNodeContents must be
an instance of Node
I've build in a way to copy it on IOS devices too, because the normal copy command don't works:
function copyUrl(e) {
var tmp = jQuery("<input>");
jQuery("body").append(tmp.val(e));
if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
var editable = tmp.contentEditable;
var readOnly = tmp.readOnly;
tmp.contentEditable = true;
tmp.readOnly = false;
var range = document.createRange();
range.selectNodeContents(tmp);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
tmp.setSelectionRange(0, 999999);
tmp.contentEditable = editable;
tmp.readOnly = readOnly;
} else {
tmp.select();
}
document.execCommand("copy");
tmp.remove();
alert("Link copied successfully!")
}
div {
padding: 30px;
}
a {
border: 1px solid;
padding: 12px 10px;
cursor: pointer;
}
a:hover {
border-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<a class="btn-floating" onclick="copyUrl('google.de')">Share</a>
</div>
What have I missed?
If you pass the JQuery element as an argument element, it will give
the TypeError you are getting because it does not interface the Node.
The TypeError message is related to you not doing one of the following.
// copy(document.getElementByClass("")[0];
copy(document.getElementById("")); // Pure JS
copy($("#")[0]); // JQuery
Example, as asked for a link passing a variable string: It creates an element then removes it after selecting it and copying the variable's value we inserted in it.
I suggest looking into the library Cliboard.js
function copy(href) {
var dummy = document.createElement("input");
document.body.appendChild(dummy);
dummy.setAttribute('value', href);
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
Copy
FROM IOS Copy to clipboard using Javascript in iOS
var copy = function(href) {
var input = document.createElement("input");
document.body.appendChild(input);
input.setAttribute('value', href);
var isiOSDevice = navigator.userAgent.match(/ipad|iphone/i);
if (isiOSDevice) {
var editable = input.contentEditable;
var readOnly = input.readOnly;
input.contentEditable = true;
input.readOnly = false;
var range = document.createRange();
range.selectNodeContents(input);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
input.setSelectionRange(0, 999999);
input.contentEditable = editable;
input.readOnly = readOnly;
document.body.removeChild(input);
} else {
input.select();
}
document.execCommand('copy');
document.body.removeChild(input);
}
I think this works on ios
Copy text
Try something like this:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('.copy-to-clipboard input').click(function() {
$(this).focus();
$(this).select();
document.execCommand('copy');
alert('Copy to Clipboard!');
});
});
</script>
<span class="copy-to-clipboard">
<input id="copy-test" readonly type="text" value="google.de">
</span>
Try this one
/*
Copy text from any appropriate field to the clipboard
By Craig Buckler, #craigbuckler
use it, abuse it, do whatever you like with it!
*/
(function() {
'use strict';
// click events
document.body.addEventListener('click', copy, true);
// event handler
function copy(e) {
// find target element
var
t = e.target,
c = t.dataset.copytarget,
inp = (c ? document.querySelector(c) : null);
// is element selectable?
if (inp && inp.select) {
// select text
inp.select();
try {
// copy text
document.execCommand('copy');
inp.blur();
// copied animation
t.classList.add('copied');
setTimeout(function() { t.classList.remove('copied'); }, 1500);
}
catch (err) {
alert('please press Ctrl/Cmd+C to copy');
}
}
}
})();
div {
padding: 30px;
}
a {
border: 1px solid;
padding: 12px 10px;
cursor: pointer;
}
a:hover {
border-color: blue;
}
<div>
<input style="position: absolute;
height: 100px;
width: 100px;
right: -150px;
top: -150px;overflow:hidden;" type="text" id="website" value="http://hpecas.com/teste" />
<a class="btn-floating" href="#" data-copytarget="#website">Share</a>
</div>

Unable to select, copy, delete or edit text in textarea in IE

I have a textarea where share link gets displayed. It works fine on Chrome and Mozilla, but in IE text cannot be selected (consequently it cannot be copied). You can edit it (delete and write).
I added the textarea with:
exports.setTextArea = function(url) {
$('.share .clipboard textarea').text(url);
$('.share .clipboard textarea').height(1);
window.setTimeout(function(){$('.share .clipboard textarea').height($('.share .clipboard textarea')[0].scrollHeight);}, 0);
}
exports.copyResult = function() {
$('.share .clipboard textarea').focus();
$('.share .clipboard textarea')[0].setSelectionRange(0, 9999);
document.execCommand('copy');
}
$(function () {
$('.share .exit-btn').on('click touchstart', shareControl.close);
$('.share textarea').keydown(function(e){
if (e.keyCode == 65 && e.ctrlKey) {
e.target.select()
}
});
});
textarea {
width: 100%;
max-height: 230px;
resize: none;
overflow: auto;
-webkit-user-select: all;
-moz-user-select: all;
-ms-user-select: all;
user-select: all;
}
<div class="clipboard">
<textarea id="textarea"></textarea>
</div>
Can it be javascript that is causing the problems? I'm using it to generate textm set text in textarea and in the and copy it to the clipboard.
Edit: I found out that this problem remains no matter where I try to place . It's specific to IE and Edge apparently although it works when tested on jsfiddle.net
After changing this:
<body onload="htmlInit('XYZ');" onselectstart="if ((event.target || event.srcElement).nodeName !== 'INPUT') return false;"...>
to this:
<body onload="htmlInit('XYZ');" onselectstart="if ((event.target || event.srcElement).nodeName !== 'INPUT' && (event.target || event.srcElement).nodeName !== 'TEXTAREA') return false;"...>
the textarea is working as expected

Convert jquery script to pure javascript

Here's the script I have:
I would like to convert it to pure JavaScript, so I won't have to use jQuery.
if ( $('#movie.playing').length ) {
$('.settings').click();
$('<style> .element { display: none; } </style>').appendTo(document.head);
$('.item').click(function() {
if ($(this).text().trim() === "Ann") {
if ($(this).attr('aria-checked') == 'true') {
$('.element').css('display', 'block');
} else {
$('.element').css('display', 'none');
}
}
});
}
Here's what I have so far:
var movie = document.querySelector("#movie_player.playing-mode");
if ( movie ) {
document.querySelector(".settings").click();
var style = document.createElement("text/css");
style.styleSheet.cssText = ".element { display: none; }";
document.head.appendChild(style);
document.querySelector(".item").click(function() {
/* what do I do with this part? */
if ($(this).text().trim() === "Ann") {
if ($(this).attr('aria-checked') == 'true') {
$('.element').css('display', 'block');
} else {
$('.element').css('display', 'none');
}
}
});
}
I don't know how to convert the if-statement, where on click of the button with text "Ann" it is going to switch the elements from display: block to none and vice versa.
$(selector) = document.querySelector(selector)
$(selector).click() = document.querySelector(selector)(maybe cache the element first).addEventlistener(eventType, fn)
css stuff can be add as 'class' like el.classList.add(someClassName).
UPDATE
It's better to get the basic knowledge with JavaScript | MDN. Personal it's easy than jQuery.

Disable text selection dynamically per click via javascript?

I have a table which I've added some multiple selection functionality where shift + click selects rows between the first click and second click but it ends up highlighting all text between the rows.
I don't want to disable text selection via CSS because this stuff really does need to be selectable, just not when shift + clicking when my multi-select function fires.
Can this be done?
var lastChecked;
$("#contact_table tr").click(function(e) {
if (e.target.getAttribute('type') == 'checkbox') {
return;
};
if (e.shiftKey && lastChecked) {
// select between last point and new point
var tableRows = $("#contact_table tr");
var newRow = tableRows.index($(this));
var oldRow = tableRows.index(lastChecked);
if (oldRow < newRow) {
newRow = newRow +1;
}
var sliceRange = [newRow, oldRow].sort();
var selectedRows = tableRows.slice(sliceRange[0], sliceRange[1])
.find('input[type=checkbox]').attr('checked', true);
} else {
var checkbox = $(this).find('input[type=checkbox]');
var checked = toggleCheckbox(checkbox);
if (checked) {
lastChecked = $(this);
}
};
recalculateSelectedButton();
});
You can deselect all text with javascript; add a call to RemoveSelection() after you run the multi-select logic.
From http://help.dottoro.com/ljigixkc.php via Clear a selection in Firefox
function RemoveSelection () {
if (window.getSelection) { // all browsers, except IE before version 9
var selection = window.getSelection ();
selection.removeAllRanges ();
}
else {
if (document.selection.createRange) { // Internet Explorer
var range = document.selection.createRange ();
document.selection.empty ();
}
}
}
You can try disabling user select based on the number of checked checkboxes. If there are any, just add the CSS style user-select: none; (and prefixed versions) to the #contact_table.
If you provide a jsfiddle with your current javascript code and table, I'd test the code too - now it's as-is ;) I'm not sure how the click interactions will play out with any cancelled event bubbling etcetera. Also, this implementation doesn't take into account that users might want to select text even if there's a checked checkbox (so it might not be what you're looking for).
$(function() {
var $contactTable = $("#contact_table"),
userSelectNoneClass = "user-select-none";
$contactTable.on("change", ":checkbox", function(e) {
var numberOfCheckedRows = $("#contact_table :checkbox:checked").length,
anyCheckedRows = (numberOfCheckedRows > 0);
if (anyCheckedRows && $contactTable.hasClass(userSelectNoneClass)) {
$contactTable.addClass(userSelectNoneClass);
} else {
$contactTable.removeClass(userSelectNoneClass);
}
});
});
.user-select-none
{
/* From https://stackoverflow.com/questions/826782/css-rule-to-disable-text-selection-highlighting */
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
Edit: using the change event instead.

How to prevent the double-click select text in Javascript

Say I have an ul (li) list in the page:
<ul>
<li>xxx<li>
<li>xxx<li>
</ul>
The element li are clickable and double-clickable, they are attached with these events, and I return false in both of them.
$('ul li').on('click',function(){
//do what I want
return false;
}).on('dblclick',function(){
//do what I want
return false;
});
But when the user double-clicks the element, the text inside the li will be selected. How can this be prevented?
Update:
Solved now,I use the following code with the css selector by NiftyDude:
$('ul li').on('click',function(){
//do what I want
return false;
}).....on('dragstart',function(){return false;}).on('selectstart',function(){return false;});
You can disable text selection using css (Note that this will effectively disable all selection methods and not just double clicking)
ul li {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
http://jsfiddle.net/T3d7v/1/
You can't stop the select from happening but you can clear the selection right after it's made:
<script type="text/javascript">
document.ondblclick = function(evt) {
if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();
}
</script>
To also prevent selecting whole paragraph by "triple click", here is the required code:
var _tripleClickTimer = 0;
document.ondblclick = function(evt) {
ClearSelection();
window.clearTimeout(_tripleClickTimer);
//handle triple click selecting whole paragraph
document.onclick = function() {
ClearSelection();
};
_tripleClickTimer = window.setTimeout(function() {
document.onclick = null;
}, 1000);
};
function ClearSelection() {
if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();
}
Source/Live test.
This should work on any browser, please report any browser where it's not working.

Categories

Resources