How to Prevent/disable copy and paste in Tinymce - javascript

I am setting up the tinymce on my system, and want to disable the copy and paste for the user in the tinymce editor, but no where I find the solution. How can I disable the copy paste in tinymce
I have implemented the
Disable pasting text into HTML form
But it is working only in simple text area but not in tinymce textarea
<script>
// Register onpaste on inputs and textareas in browsers that don't
// natively support it.
(function () {
var onload = window.onload;
window.onload = function () {
if (typeof onload == "function") {
onload.apply(this, arguments);
}
var fields = [];
var inputs = document.getElementsByTagName("input");
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < inputs.length; i++) {
fields.push(inputs[i]);
}
for (var i = 0; i < textareas.length; i++) {
fields.push(textareas[i]);
}
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
if (typeof field.onpaste != "function" && !!field.getAttribute("onpaste")) {
field.onpaste = eval("(function () { " + field.getAttribute("onpaste") + " })");
}
if (typeof field.onpaste == "function") {
var oninput = field.oninput;
field.oninput = function () {
if (typeof oninput == "function") {
oninput.apply(this, arguments);
}
if (typeof this.previousValue == "undefined") {
this.previousValue = this.value;
}
var pasted = (Math.abs(this.previousValue.length - this.value.length) > 1 && this.value != "");
if (pasted && !this.onpaste.apply(this, arguments)) {
this.value = this.previousValue;
}
this.previousValue = this.value;
};
if (field.addEventListener) {
field.addEventListener("input", field.oninput, false);
} else if (field.attachEvent) {
field.attachEvent("oninput", field.oninput);
}
}
}
}
})();
</script>
</head>
<body>
<!-- Not Working here-->
<textarea class="tinymce" onpaste="return false;"></textarea>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="plugin/tinymce/tinymce.min.js"></script>
<script type="text/javascript" src="plugin/tinymce/init-tinymce.js"></script>
<!-- Working here-->
<textarea onpaste="return false;"></textarea>
</body>
I expect that, it should work in the textarea of tinymce,
Thank you in advance, I will be very gratefull

have you tried to prevent the default
document.addEventListener('paste', function(e){
e.preventDefault();
});
I also read that you can intercept paste in the tinymce.init
paste_preprocess: function(plugin, args) {
console.log(args.content);
args.content = '';
}
Hope that one of those methods works out for you

Related

Input to make "Enter" forbidden

I have a HTML input in my site and i want to make "ENTER" forbidden in this box.
I mean user should not be able to enter into the box and if the user pasted some text, the enters gets converted to "space character" auto.
you can put this in the onchange of the text input/textarea
var text = document.forms[0].txt.value;
text = text.replace(/\r?\n/g, '');|
put this inside your header script tags and you should be good.
<script type="text/javascript" language="javascript">
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA')
for(var i = 0, l = txts.length; i < l; i++) {
var func = function() {
var text = this.value;
text = text.replace(/\r?\n/g, '');
this.value = text;
}
txts[i].onkeyup = func;
txts[i].onblur = func;
}
}
</script>
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
Uses setTimeout and clearTimeout
<input type='text' id='text'>
var timer = null;
$('#text').keydown(function(){
clearTimeout(timer);
timer = setTimeout(doStuff, 1000)
});
function doStuff() {
alert('do stuff');
}
use the doStuff() function to execute code 1 second after user stops typing

placeholder javascript fallback for textarea not working

The below is the html code:
<textarea name="test" rows="5" cols="20" placeholder="Brief description of your requirement,project, concept or idea"></textarea>
<script>
$(function() {
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
if (!supports_input_placeholder()) {
var fields = document.getElementsByTagName('textarea');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('placeholder')) {
fields[i].defaultValue = fields[i].getAttribute('placeholder');
fields[i].onfocus = function() {
if (this.value == this.defaultValue)
this.value = '';
}
fields[i].onblur = function() {
if (this.value == '')
this.value = this.defaultValue;
}
}
}
}
});
</script>
Please help me point out the mistake. placeholder fallback functionality is not working.I have been debugging it from long time.
Below is the link for fiddle:
check the functionality in ie9 and below as they doesn't support placeholder attribute:
http://jsfiddle.net/DxcYW/
Thanks
Here it is in pure JavaScript:
(function (D, undefined) {
'use strict';
var i, length, placeholder, textareas;
function hidePlaceHolder (placeholder) {
return function (e) {
var target;
target = e.target || e.srcElement;
if (target.value === placeholder) {
target.value = '';
}
};
}
function showPlaceHolder (placeholder) {
return function (e) {
var target;
target = e.currentTarget || e.srcElement;
if (target.value === '') {
target.value = placeholder;
}
};
}
if (! ('placeholder' in D.createElement('textarea'))) {
textareas = D.getElementsByTagName('textarea');
length = textareas.length;
for (i = 0; i < length; i += 1) {
placeholder = textareas[i].getAttribute('placeholder');
textareas[i].value = placeholder;
if (textareas[i].addEventListener) {
textareas[i].addEventListener('focus', hidePlaceHolder(placeholder));
textareas[i].addEventListener('blur', showPlaceHolder(placeholder));
} else {
textareas[i].attachEvent('onfocus', hidePlaceHolder(placeholder));
textareas[i].attachEvent('onblur', showPlaceHolder(placeholder));
}
}
}
}(document));
try putting your JS in
<script> ... </script>
tags. :)
My findings and solution:
Input fields have value attribute but TEXTAREA doesn't have it.
So when we use inputObj.defaultValue="sometext" for input tag it sets the default value as well as current value to sometext, if we dont define the attribute value="something" in the input tag.This works fine from ie9 and above. For below versions if we don't define value="sometext" inputObj.defaultValue="sometext" won't set current value as the default value by itself. For this we can do two things:
we have to manually give value="something which is equal to placeholder text"
we can get the value of placeholder through javascript and set the value from there.
This is not the case with textarea. Textarea doesn't have a attribute value. So when we use textareaObj.defaultValue="sometextarea text" then the default value is set to the given text but not the value itself as we don't have value attribute.value in textarea is nothing but the content between the textarea tags.
Difference between defaultvalue and value:
default value remains the same once it is set.
value is the current value which is being modified by javascript or ourself my typing into the textfield.
For my above issue I found a workaround just by adding one more line to my code:
<textarea name="test" rows="5" cols="20" placeholder="Brief description of your requirement,project, concept or idea"></textarea>
<script>
$(function() {
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
if (!supports_input_placeholder()) {
var fields = document.getElementsByTagName('textarea');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('placeholder')) {
fields[i].defaultValue = fields[i].getAttribute('placeholder');
fields[i].value = fields[i].getAttribute('placeholder');//setting the value
fields[i].onfocus = function() {
if (this.value == this.defaultValue)
this.value = '';
}
fields[i].onblur = function() {
if (this.value == '')
this.value = this.defaultValue;
}
}
}
}
});
</script>
Thank you guys for your quick replies and I pity the guy who voted down the question. I feel it is a good question. isn't it ?

Need Help In Javascript Text Typer Effect

I have a javascript text typer code:
CSS:
body
{
background-color:black;
}
#writer
{
font-family:Courier;
font-size:12px;
color:#24FF00;
background-color:black;
}
Javascript:
var text = "Help Please, i want help.";
var counter = 0;
var speed = 25;
function type()
{
lastText = document.getElementById("writer").innerHTML;
lastText+=text.charAt(counter);
counter++;
document.getElementById("writer").innerHTML = lastText;
}
setInterval(function(){type()},speed);
HTML:
<div id="writer"></div>
I want to know how can i use <br> tag (skipping a line or moving to another line). I tried many ways but failed, I want that if I Typed My name is Master M1nd. and then i want to go on the other line how would i go?
I've made a jQuery plugin, hope this will make things easier for you. Here is a live demo : http://jsfiddle.net/wared/V7Tv6/. As you can see, jQuery is loaded thanks to the first <script> tag. You can then do the same for the other <script> tags if you like, this is not necessary but considered as a good practice. Just put the code inside each tag into separate files, then set appropriate src attributes in the following order :
<script src=".../jquery.min.js"></script>
<script src=".../jquery.marquee.js"></script>
<script src=".../init.js"></script>
⚠ Only tested with Chrome ⚠
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
jQuery.fn.marquee = function ($) {
function findTextNodes(node) {
var result = [],
i = 0,
child;
while (child = node.childNodes[i++]) {
if (child.nodeType === 3) {
result.push(child);
} else {
result = result.concat(
findTextNodes(child)
);
}
}
return result;
}
function write(node, text, fn) {
var i = 0;
setTimeout(function () {
node.nodeValue += text[i++];
if (i < text.length) {
setTimeout(arguments.callee, 50);
} else {
fn();
}
}, 50);
}
return function (html) {
var fragment, textNodes, text;
fragment = $('<div>' + html + '</div>');
textNodes = findTextNodes(fragment[0]);
text = $.map(textNodes, function (node) {
var text = node.nodeValue;
node.nodeValue = '';
return text;
});
this.each(function () {
var clone = fragment.clone(),
textNodes = findTextNodes(clone[0]),
i = 0;
$(this).append(clone.contents());
(function next(node) {
if (node = textNodes[i]) {
write(node, text[i++], next);
}
})();
});
return this;
};
}(jQuery);
</script>
<script>
jQuery(function init($) {
var html = 'A <i>marquee</i> which handles <u><b>HTML</b></u>,<br/> only tested with Chrome. Replay';
$('p').marquee(html);
$('a').click(function (e) {
e.preventDefault();
$('p').empty();
$('a').off('click');
init($);
});
});
</script>
<p></p>
<p></p>
Instead of passing <br> char by char, you can put a \n and transform it to <br> when you modify the innerHTML.
For example (http://jsfiddle.net/qZ4u9/1/):
function escape(c) {
return (c === '\n') ? '<br>':c;
}
function writer(text, out) {
var current = 0;
return function () {
if (current < text.length) {
out.innerHTML += escape(text.charAt(current++));
}
return current < text.length;
};
}
var typeNext = writer('Hello\nWorld!', document.getElementById('writer'));
function type() {
if (typeNext()) setInterval(type, 500);
}
setInterval(type, 500);
Also probably you'll be interested in exploring requestAnimationFrame (http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/), for your typing animation :)

How to send Keyboard events (e.g. Backspace, Delete) in Safari from Javascript

I'm implementing an on-screen Keyboard for a Javascript application. The text should appear in a textarea-Element. I've no problem creating text-events but feel unable to create non-text events such as the Backspace. Here is some sample code:
<html>
<head>
<title>Test Textarea Events</title>
<script type="text/javascript">
function log(text) {
var elem = document.getElementById("log");
if (elem) {
elem.innerHTML += "<br/>" + text;
}
}
function logEvent(e) {
log("Type: " + e.type + ", which: " + e.which + ", keyCode: " + e.keyCode + ", charCode: " + e.charCode + ", keyIdentifier: " + e.keyIdentifier + ", data: " + e.data);
}
function logClear() {
var elem = document.getElementById("log");
if (elem) {
elem.innerHTML = "";
}
}
function sendBackEvent() {
var textarea = document.getElementById("textarea");
if(!textarea) {
return;
}
var ke1 = document.createEvent("KeyboardEvent");
ke1.initKeyboardEvent("keydown", true, true, window, "U+0008", 0, ""); // U+0008 --> Backspace
// how to set "keyCode" and "which"?
// 1. ke1.keyCode = 8; will be ignored due to "writable: false"
// 2. delete ke1.keyCode will be ignored too
// and Object.defineProperty(KeyboardEvent.prototype, "keyCode", ... whatever ...);
// will result in Exception due to "configurable: false"
// 3. generating a more general Event (e.g. "var e = document.createEvent("Events");")
// and setting all necessary props (e.g. "e.initEvent("keydown", true, true);e.keyCode=8;e.which=8;")
// will work, but the textarea will ignore the Event
textarea.dispatchEvent(ke1);
var ke2 = document.createEvent("KeyboardEvent");
ke2.initKeyboardEvent("keyup", true, true, window, "U+0008", 0, ""); // U+0008 --> Backspace
// same question as above
textarea.dispatchEvent(ke2);
}
function init() {
var textarea = document.getElementById("textarea");
if(!textarea) {
return;
}
textarea.addEventListener("keydown", logEvent, false);
textarea.addEventListener("keypress", logEvent, false);
textarea.addEventListener("keyup", logEvent, false);
textarea.addEventListener ("textInput", logEvent, false);
}
</script>
</head>
<body onload="init()">
<textarea id="textarea" name="text" cols="100" rows="20"></textarea><br/><br/>
<button onclick="sendBackEvent()">send BackEvent</button>
<button onclick="logClear()">clear log</button><br/>
<div id="log"></div>
</body>
</html>
The interesting function here is sendBackEvent(). I tried hard to get exactly the same event like pressing the Backspace-Button on the physical Keyboard but didn't succeed.
I know there is a Webkit-Bug but hoped there could be some other way to get this working. Has anyone had the same problem? Could it be solved? How? The proposed solution here (calling new KeyboardEvent(...) ) doesn't work because directly calling the KeyboardEvent constructor results in following exception:
Exception: TypeError: '[object KeyboardEventConstructor]' is not a constructor (evaluating 'new KeyboardEvent(...)')
I have no more ideas.
Since there seem to no way out, i found myself constrained to install my own backspace event handler. The working code (without logging now) is here:
<html>
<head>
<title>Test Textarea Events</title>
<script type="text/javascript">
function sendBackEvent() {
var textarea = document.getElementById("textarea");
if(!textarea) {
return;
}
var ke1 = document.createEvent("Events");
ke1.initEvent("keydown", true, true);
ke1.keyCode = ke1.which = 8; // Backspace
textarea.dispatchEvent(ke1);
var ke2 = document.createEvent("Events");
ke2.initEvent("keyup", true, true);
ke2.keyCode = ke2.which = 8; // Backspace
textarea.dispatchEvent(ke2);
}
function handleBackEvent(e) {
if(e.keyCode != 8) {
return;
}
if (textarea.value.length == 0) {
return;
}
var text = textarea.value;
var selectionStart = textarea.selectionStart;
var selectionEnd = textarea.selectionEnd;
if (selectionStart < selectionEnd) {
var text1 = (selectionStart > 0 ? text.slice(0, selectionStart) : "");
var text2 = (selectionEnd < text.length ? text.slice(selectionEnd) : "");
textarea.value = text1 + text2;
}
else if (selectionStart > 0) {
var text1 = (selectionStart - 1 > 0 ? text.slice(0, selectionStart - 1) : "");
var text2 = (selectionStart < text.length ? text.slice(selectionStart) : "");
textarea.value = text1 + text2;
selectionStart--;
}
textarea.selectionStart = textarea.selectionEnd = selectionStart;
e.preventDefault();
e.stopPropagation();
return false;
};
var textarea;
function init() {
textarea = document.getElementById("textarea");
if(!textarea) {
return;
}
textarea.addEventListener("keydown", handleBackEvent, false);
}
</script>
</head>
<body onload="init()">
<textarea id="textarea" name="text" cols="100" rows="20"></textarea><br/><br/>
<button onclick="sendBackEvent()">send BackEvent</button>
</body>
</html>
Just in case someone else run into same trouble.

Javascript Focus() function not working

I have a textbox which I want to set the focus on, but it doesn't work.
document.getElementById("txtCity").focus();
Any idea?
Maybe you are calling the JavaScript before the input element is rendered? Position the input element before the JavaScript or wait until the page is loaded before you trigger your JavaScript.
In that order, it works just fine:
<input type="text" id="test" />
<script type="text/javascript">
document.getElementById("test").focus();
</script>
In jQuery you could place your code within the .ready() method to execute your code first when the DOM is fully loaded:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#test").focus();
// document.getElementById("test").focus();
});
</script>
In case someone searching has a similar situation to mine ... I had to set a tabindex attribute before my div could receive focus():
featured.setAttribute('tabindex', '0');
featured.focus();
console.log(document.activeElement===featured); // true
(I found my answer here: Make div element receive focus )
And of course, make sure the body element is ready before setting focus to a child element.
I have also faced same problem.To resolve this problem, put your code in setTimeout function.
function showMeOnClick() {
// Set text filed focus after some delay
setTimeout(function() { jQuery('#searchTF').focus() }, 20);
// Do your work.....
}
Try to wrap it into document ready function and be sure, that you have jquery included.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#test").focus();
});
</script>
<div id="txtROSComments" contenteditable="true" onkeyup="SentenceCase(this, event)"style="border: 1px solid black; height: 200px; width: 200px;">
</div>
<script type="text/javascript">
function SentenceCase(inField, e) {
debugger;
var charCode;
if (e && e.which) {
charCode = e.which;
} else if (window.event) {
e = window.event;
charCode = e.keyCode;
}
if (charCode == 190) {
format();
}
}
function format() {
debugger; ;
var result = document.getElementById('txtROSComments').innerHTML.split(".");
var finaltxt = "";
var toformat = result[result.length - 2];
result[0] = result[0].substring(0, 1).toUpperCase() + result[0].slice(1);
if (toformat[0] != " ") {
for (var i = 0; i < result.length - 1; i++) {
finaltxt += result[i] + ".";
}
document.getElementById('txtROSComments').innerHTML = finaltxt;
alert(finaltxt);
abc();
return finaltxt;
}
if (toformat[0].toString() == " ") {
debugger;
var upped = toformat.substring(1, 2).toUpperCase();
var formatted = " " + upped + toformat.slice(2);
for (var i = 0; i < result.length - 1; i++) {
if (i == (result.length - 2)) {
finaltxt += formatted + ".";
}
else {
finaltxt += result[i] + ".";
}
}
}
else {
debugger;
var upped = toformat.substring(0, 1).toUpperCase();
var formatted = " " + upped + toformat.slice(1);
for (var i = 0; i < result.length - 1; i++) {
if (i == (result.length - 2)) {
finaltxt += formatted + ".";
}
else {
//if(i
finaltxt += result[i] + ".";
}
}
}
debugger;
document.getElementById('txtROSComments').value = finaltxt;
return finaltxt;
}
</script>
<script type="text/javascript">
function abc() {
document.getElementById("#txtROSComments").focus();
}
It works fine in this example
http://jsfiddle.net/lmcculley/rYfvQ/

Categories