Change Colour Of Text When Ctrl-c And Ctrl-v Are Pressed
I want change text of html text when CTRL-C and CTRL-V are clicked. I have this code that changes the text when CTRL-C is clicked but when I copy other text, the previous text does
Solution 1:
You can opt to reset the color, each time before applying the new color. See snippet below:
$(document).ready(function() {
var ctrlDown = false,
ctrlKey = 17,
cmdKey = 91,
vKey = 86,
cKey = 67;
$(document).keydown(function(e) {
if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true;
}).keyup(function(e) {
if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false;
});
// Document Ctrl + C/V
$(document).keydown(function(e) {
var clip = document.getElementById("clipBoard");
if (ctrlDown && (e.keyCode == cKey)) {
navigator.clipboard.readText()
.then(text => {
clip.value = text;
var sel = window.getSelection();
var range = 0;
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
// Set design mode to ondocument.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
//reset all custom color edits
$('font').removeAttr('color');
// Colorize textdocument.execCommand("ForeColor", false, "red");
// Set design mode to offdocument.designMode = "off";
})
.catch(err => {
});
console.log("Document catch Ctrl+C");
}
if (ctrlDown && (e.keyCode == vKey)) {
console.log("Document catch Ctrl+V");
}
});
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><p>Enter text here and copy</p><spanid="content"contenteditable>Test words to copy and paste</span><br><br><p>This is the text in the clipboard</p><textareaid="clipBoard"readonly></textarea>
Note: Tested only Chrome 78
Post a Comment for "Change Colour Of Text When Ctrl-c And Ctrl-v Are Pressed"