I have overridden the paste
event. I noticed that because the event's default behavior is prevented, it is not currently possible to undo the "paste" with Ctrl+Z.
$(this).on('paste', function (evt) {
// Get the pasted data via the Clipboard API.
// evt.originalEvent must be used because this is jQuery, not pure JS.
// https://stackoverflow.com/a/29831598
var clipboardData = evt.originalEvent.clipboardData || window.clipboardData;
var pastedData = clipboardData.getData('text/plain');
// Trim the data and set the value.
$(this).val($.trim(pastedData));
// Prevent the data from actually being pasted.
evt.preventDefault();
});
Is there a way to override the undo functionality or do the above differently such that Ctrl+Z will work?
You can perform undo and redo by 'CTRL+Z' and 'CTRL+Y' keyboard shortcuts. Document Editor exposes API to do it programmatically.
Copy and Paste Text // copy text TO the clipboard await navigator. clipboard. writeText('This text is now in the clipboard'); // get text FROM the clipboard let text = await navigator. clipboard.
Use
document.execCommand("insertText", false, $.trim(pastedData));
instead of
$(this).val($.trim(pastedData));
It will preserve the undo history.
$('#inputElement').on('paste', function (evt) {
var clipboardData = evt.originalEvent.clipboardData || window.clipboardData;
var pastedData = clipboardData.getData('text/plain');
this.select(); // To replace the entire text
document.execCommand("insertText", false, $.trim(pastedData));
evt.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="inputElement"></textarea>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With